Bash has a yank-last-arg
command for working with your command history:
yank-last-arg (M-. or M-_)
Insert last argument to the previous command (the last word of the previous history entry). With a numeric argument, behave exactly like yank-nth-arg
. Successive calls to yank-last-arg
move back through the history list, inserting the last word (or the word specified by the argument to the first call) of each line in turn. Any numeric argument supplied to these successive calls determines the direction to move through the history. A negative argument switches the direction through the history (back or forward). The history expansion facilities are used to extract the last argument, as if the !$
history expansion had been specified.
With the default keybindings, you can activate it by pressing Meta..1 That copies the last word of your most recent command to where your cursor is.
To copy the nth word instead of the last word, press Metan, then Meta..
I find that this is easier to use and is less error-prone than history expansion, since it works interactively.
Another way to tweak a previous command interactively is to use the edit-and-execute-command
feature:
edit-and-execute-command (C-x C-e)
Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL
, $EDITOR
, and emacs
as the editor, in that order.
Use the up/down arrow keys to recall the command, then press CtrlX, CtrlE to open that command in your $EDITOR
. You can then edit the command to your liking, then when you save and exit the editor, it will execute.
1 Depending on your keyboard layout, Meta could mean holding down an Alt key, holding down an Option key, or pressing and releasing the Esc key. The . is the period or full-stop character, in case you have difficulty reading it here.
la -a /path/to/somewhere
and use$_
or!$
to get that last argument. That would work for any case that doesn't have multiple positional arguments.Alt+<digit>
thenAlt+.
to substitute the<digit>
argument.