Bash History: Re-use and Edit Previous Commands - Examples and Reference

Last updated:

These are some little tips and hacks you can use to enhance your productivity while working on bash.

It might seem a small contribution to justify learning yet another tool but, when put together, all these things will probably help you make more effective use of your time.

Search for a command containing a string

hit Ctrl + r:


Then start typing. For example, if you type cd, you would probably see something like this (cd /etc/apache2 was the last command I ran using cd, that's why it show up first)

(reverse-i-search) cd: cd /etc/apache2/

To see the next matches, hit Ctrl+r again as many times as you want. When you find the command you want, hit tab so it'll be available for you to edit or run it.

Run your last command again using sudo

If you get a permission denied-like error after running a command and you have access to sudo, do this to run the last command using super user privileges:

$ sudo !!

Run your last command again replacing strings

(example using svn commands)

$ svn diff path/to/my/file.txt

After seeing the diff result, say you want to commit that very same file. Just replace "diff" with "commit" in the last command:

$ !!:gs/diff/commit/
svn commit path/to/my/file.txt


Dialogue & Discussion