How can I get a specific argument from a previous command in bash?
In bash, you can use !*
to get all the arguments from the previous command. As an example, if you did cp /some/path /some/other/path
and then did mv !*
, the second command would be expanded to mv /some/path /some/other/path
.
Is there anything like this that can be used to access a specific argument from a command instead of all of them?
Solution 1:
In !*
, !
is the history expansion prefix, and *
is the word designator that means all arguments. You can memorize the general syntax as bang-line-colon-column (!
line:
column). There are many possible shortcuts: the default line is the previous line, the default column specifier is “all”, and you can leave off the colon if the column specifier is non-numeric (but !3
would mean line 3). You can use !:0
to refer to the command name, !:1
, !:2
, etc, to refer to successive arguments, !:$
for the last word, !:*
for all arguments, and more.
See also this post by Michael Mrozek at Unix Stack Exchange.
Solution 2:
Personally, I really dislike this “expansion with exclamation mark” feature which will even disturb if you try echo "Hello World!"
in interactive shells (so sourcing scripts that assume they will be run in non-interactive mode won't work at all).
So, I set set +o histexpand
and start recalling arguments with the following method:
Esc, 1, Esc, Ctrl-Y => Insert first argument of previous command.
Note that the Esc-trick is because I don't have a meta key.