How can I get a specific argument from a previous command in bash?

31

18

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?

Wuffers

Posted 2010-11-14T23:12:07.777

Reputation: 16 645

Answers

38

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.

Gilles 'SO- stop being evil'

Posted 2010-11-14T23:12:07.777

Reputation: 58 319

1I tried it myself and this didn't work, however. After looking at the post by Michale Mrozek, it says to use !:1, !:2. After using the version with the colons, it worked. – Wuffers – 2010-11-14T23:41:00.003

@MrMan: Oops, right, if you leave off the colon with a number, the number is interpreted as a line number. Sorry about that. – Gilles 'SO- stop being evil' – 2010-11-15T18:57:24.030

No problem. So, then I assume that doing !1:1 would point to the first argument of the first line? – Wuffers – 2010-11-17T02:00:19.533

4

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.

Benoit

Posted 2010-11-14T23:12:07.777

Reputation: 6 563

I almost never use exclamation points in commands. So the Exclamation point method works perfectly for me. – Wuffers – 2010-11-17T01:58:45.993

Then enjoy it. Many of the numerous features of your shell are designed for only a few users. – Benoit – 2010-11-17T06:29:29.350

1Actually, you don't have to escape exclamation points. Do echo 'Hello, orld!'. Note the single quotes instead of double ones. – Wuffers – 2010-11-30T23:59:30.177