Bash history expansion πŸ…

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:

  1. ls -a -r
  2. date
  3. touch a b c d e
CommandDescriptionOutput
!!last command (all words)touch a b c d e
!*last command, all argumentsa b c d e
!^last command, second argumenta
!$last command, last argumente
!:0first wordtouch
!:1second word (first argument)a
!:2-4range of wordsb c d
 ^touch^lsfind touch and replace it with ls ls a b c e d
!-1last commandtouch a b c d e
!-2previous to last commanddate
!-2:0first keyword of previous to last commanddate
!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
!lssearch for command starting from lsls -a -r
!? bsearch for command containing btouch a b c d e
!!:gs/a/p/last command, replace a with btouch p b c d e

References:

Book recommendation:

  • UNIX Shells by Example, Ellie Quigley