Sean Walberg’s blog

BASH History Expansion

Jan24th, 20132:22 pm

The Unix shell has a whole bunch of features to make your life easier. One has to do with the history. Some I have managed to ingrain into muscle memory, others I have to remember which often means I do it the long way. I hope these examples help you out.

123456789101112131415161718192021222324252627282930

# Start off with some files$ touch one two three four
# !$ expands to all the arguments from the last command$ ls !*
ls one two three four
four one three two
# !foo runs the last command that starts with foo$ !touch
touch one two three four
# Carat (^) does a search/replace in the previous command$ ^touch^ls
ls one two three four
four one three two
# !$ is the last item in the previous command, !^ is the first _argument_$ head !$head four
$ ls four three two one
four one three two
$ cat !^
cat four
# !:n is the n'th item on the previous command line, 0 indexed$ ls four three two one
four one three two
$ cat !:3
cat two
$ ls four three two one
four one three two
$ which !:0
which ls
/bin/ls

There are a lot more, run a man bash and look for the section called HISTORY EXPANSION.