Bash – Inserting Last Used Argument of Current Command

argumentsbashkeyboard shortcutslinuxshell

I'm aware that you can recall the last argument of the previous command with !$ and also cycle through previous arguments with ALT + . but can you recall the last argument used for the current command that is being used?

e.g,

root@chip:/# echo peckahs
root@chip:/# *_stuffthatdoesntmatter_*
root@chip:/# *_stuffthatdoesntmatter_*
root@chip:/# *_stuffthatdoesntmatter_*
root@chip:/# echo peckahs < used key shortcut to recall 'peckahs' the last used argument for echo

Best Answer

With bash you can do nearly what you're asking for like this:

echo !echo:$

So when you do

echo This is fun
ls
echo !echo:$

the last line outputs fun. * instead of $ produces all the arguments to the matching command; so

echo This is fun
ls
echo !echo:*

outputs This is fun again; but you might as well just do

!echo

in this case.

This isn't limited to repeating a command's arguments with the same command:

printf !echo:*

See the bash reference manual for details. You could even combine this with the histverify shell option to give you a chance to check the command before it's executed, which gets you close to keyboard-interactive history-based completion.

History expansions can be used anywhere; so for example

lastechoargs="!echo:*"

stored all the arguments to the last echo command in the lastechoargs variable.

This works for complete commands too; say for example you've worked out a complex git command, and you want to save it in a file:

echo !git > mygitcommand

Or you want to archive some directories, but you decide to delete a couple of files first:

ls dir1 dir2
rm dir2/somefile
tar cpzf archive.tar.gz !ls:*