You probably know the bash history function. All commands you entered are stored in memory and will be written to
~/.bash_history as soon as you exit your current shell. You may have used this often by tapping the up and down arrow keys to repeat the last few commands. But did you know that bash can do much more history work for you?
Bash has some really advanced history functionality implemented. For instance you can type an exclamation point followed by any number to repeat a specific command. To see all recently executed commands and their numbers run
history. For instance:
$ history 501 foo 502 bar 503 history
You can now e.g. type
!502, to call the command
bar again. But you don't have to look at this command list each time. You can also count upwards from the current command line by prepending a minus sign to the number. That is,
!-3 calls the third last command again. Instead of
!-1 which re-executes the last command you can also write
But there's even more. You cannot only refer to specific numbers but also to the commands themselves. For example
would recall the last command which starts with
man. You can also look for commands which contain this string somewhere by running
This searches for the last command containing
man. The trailing question mark may be omitted if you want to search for commands, which end with that string.
Another useful feature is to re-run commands but replacing some of their contents.
would run the last command again but replace
Even more interesting are modifiers. With modifiers you can extend your event designators (i.e. the exclamation point expression). A modifier is added by appending a colon and the modifier itself. One modifier that is very handy is the search and replace modifier
:s. To run the third last command but replacing the first occurrence of
You see that
^search^replace^ is only a shorthand for
!!:s/search/replace/, respectively. To repeat the last replacement you may use the modifier
There are plenties of other modifiers and also so-called word designators which can be used to refer to specific parts of a command. I can't cover them all in this blog post but have a look at the man page for
One last thing to mention: if you don't want some commands to be added to your history just add them to your
HISTIGNORE environment variable. This variable contains a colon (
:) separated list of all commands to be excluded from the history. And of course don't forget to clean up your history from time to time or lower the maximum number of stored commands by changing the value of the
HISTSIZE environment variable.
Read more about bash history functions:
- About.com: history man page
- GNU.org: Using History Interactively
- Linux.com: Using command history in the bash shell