> /dev/null

Interesting hacks, snippets, and shortcuts.

Oct 24

Using arguments from the previous command

One of my favorite bash tricks is the ability to grab the last argument of the previous command with <ESC>.

$ vim program.sh
$ chmod +x <ESC>.
$ ./<ESC>.

But what if you need other arguments than just the last one? You can specify an argument number. For example <ESC>1<ESC>. gets you the first argument for your command.

$ mv foo bar
$ mv <ESC>. <ESC>1<ESC>. # rename bar back to foo

As a bonus, <ESC>0<ESC>. gets the previous command itself.

The Meta Key

If your terminal is configured for it, you can save time by holding down the Meta key (often ALT or OPTION) while pressing the number and . instead of pressing escape.

$ mv foo bar
$ mv <ALT>+. <ALT>+1<ALT>+.

Other Methods of Accessing Arguments

This post explaining the use of !! has some great tricks for working with arguments.

The one that jumped out to me is !!* which grabs all the arguments from your previous command:

$ touch README.md .gitignore LICENSE.txt
$ git add !!*