How do you recall the last (n-th?) passed argument of the previous command you used with bash?

Often times I issue different commands on the same file. For example:

$ youtube-dl aB54c4p0eo #I made this video id up on the spot
$ mv aB54c4p0eo.flv kittens.flv
$ vlc kittens.flv
$ rm kittens.flv

Is there a way to reuse arguments from the previous command in the current so that I don’t have to rewrite it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

alt-. is certainly nice, but if you happen to already know which numbered argument you want, you can be faster: !:n is the nth argument of the previous command.

It’s often helpful to combine this with magic space. To enable that, put in your .inputrc Space: magic-space. With that enabled, when you type space after !:2, it will be immediately expanded to its value instead of waiting for you to hit enter. Saves you from accidentally grabbing the wrong argument.

Method 2

In bash you can use the shortcut Alt + ..
Hitting it once, will give you the last argument. Hitting it more will cycle through your last arguments.

Method 3

In bash, the designator for the “last word on previous command line” is !!$ :

$ echo hello world
hello world
$ echo goodbye !!$
echo goodbye world # this is bash echoing actual cmd line before execution
goodbye world

You can also use the “caret syntax” to replace the initial part of the command line; this comes handy if you want to execute several commands on the same file:

file file.dat
^file^ls -l^ #gives `ls -l file.dat`
^ls -l^stat # gives `stat file.dat`

There are many more possibilities; see “History substitution” in the bash(1) man page for details.

Method 4

In bash, you can also use $_ for the last command line argument of the last command you typed:

$ youtube-dl aB54c4p0eo #I made this video id up on the spot
$ mv aB54c4p0eo.flv kittens.flv
$ vlc kittens.flv
$ rm kittens.flv

becomes:

$ youtube-dl aB54c4p0eo #I made this video id up on the spot
$ mv $_ kittens.flv
$ vlc $_
$ rm $_

Method 5

One relatively slow way is recalling the previous command with and replacing the previous command with the newer one.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x