The general syntax is:
!command:parameter
Command segment defines which command to look for in history. It can be a modifier like !! (last command), !-1, !-2, !-3 … (last, previous to last etc) or a specific keyword like !cat (search for most recent cat).
Parameter segment defines which part of the command to use. ^ is first parameter, $ is last parameter, * are all the parameters, 0 the command and 1,2,3… are the parameters. You can define a range eg 2-4 (parameters 2 to 4)
Besides that, you can also use ^x^y^ to replace x with y. There are some more advanced ways to search. Take a look at the references at the end of this page.
You can also use history n to review the last n commands with their ids. If you know an id, you can use it at command segment,
All results are shown as if the command was executed immediately after touch a b c d e (not one after another)
Assume that you have typed in this order:
- ls -a -r
- date
- touch a b c d e
Command | Description | Output |
---|---|---|
!! | last command (all words) | touch a b c d e |
!* | last command, all arguments | a b c d e |
!^ | last command, second argument | a |
!$ | last command, last argument | e |
!:0 | first word | touch |
!:1 | second word (first argument) | a |
!:2-4 | range of words | b c d |
^touch^ls | find touch and replace it with ls | ls a b c e d |
!-1 | last command | touch a b c d e |
!-2 | previous to last command | date |
!-2:0 | first keyword of previous to last command | date |
!ls:* | search for command ls, all arguments of ls | -a -r |
!ls:^ | search for command ls, first argument of ls | -a |
!ls:$ | search for command ls, last argument of ls | -r |
!ls | search for command starting from ls | ls -a -r |
!? b | search for command containing b | touch a b c d e |
!!:gs/a/p/ | last command, replace a with b | touch p b c d e |
… | … | … |
References:
- http://www.thegeekstuff.com/2011/08/bash-history-expansion
- https://www.gnu.org/software/bash/manual/html_node/Event-Designators.html#Event-Designators
Book recommendation:
- UNIX Shells by Example, Ellie Quigley