How can I get a specific argument from a previous command in bash?
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.
Related videos on Youtube
Comments
-
Wuffers almost 2 years
In bash, you can use
!*
to get all the arguments from the previous command. As an example, if you didcp /some/path /some/other/path
and then didmv !*
, the second command would be expanded tomv /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?
-
Gilles 'SO- stop being evil' over 13 years@MrMan: Oops, right, if you leave off the colon with a number, the number is interpreted as a line number. Sorry about that.
-
Wuffers over 13 yearsI almost never use exclamation points in commands. So the Exclamation point method works perfectly for me.
-
Wuffers over 13 yearsNo problem. So, then I assume that doing
!1:1
would point to the first argument of the first line? -
Wuffers over 13 yearsActually, you don't have to escape exclamation points. Do
echo 'Hello, orld!'
. Note the single quotes instead of double ones.