Reusing an argument from the previous command

Posted on

Quite often you need to call several commands with the same argument one after another. The most common example is creating a folder and then switching into it. This can be done with the help of !$ or $_.

The former is substituted with the last word of the previous command as recorded in history and the latter is a shell parameter that expands to the last argument of the previous command:

date -u > now.txt
echo !$
date -u > now.txt
echo $_

Will print

now.txt
-u

They behave indentically if you don't have any redirections, pipes, etc. So, in our example with creating a folder and switching into it you can use either version:

mkdir tmp && cd !$ 
or
mkdir tmp && cd $_