How can I recall the argument of the previous bash command?

LinuxBashUnixCommand

Linux Problem Overview


Is there a way in Bash to recall the argument of the previous command?

I usually do vi file.c followed by gcc file.c.

Is there a way in Bash to recall the argument of the previous command?

Linux Solutions


Solution 1 - Linux

You can use $_ or !$ to recall the last argument of the previous command.

Also Alt + . can be used to recall the last argument of any of the previous commands.

Solution 2 - Linux

If the previous command had two arguments, like this

ls a.txt b.txt

and you wanted the first one, you could type

!:1

giving

a.txt

Or if you wanted both, you could type

!:1-2

giving

a.txt b.txt

You can extend this to any number of arguments, eg:

!:10-12

Solution 3 - Linux

!!:n where n is the 0-based position of the argument you want.

For example:

echo 'one' 'two'
# "one two"

echo !!:2
# "two"

The ! prefix is used to access previous commands.

Other useful commands:

  • !$ - last argument from previous command
  • !^ - first argument (after the program/built-in/script) from previous command
  • !* - all arguments from previous command
  • !! - previous command (often pronounced "bang bang")
  • !n - command number n from history
  • !pattern - most recent command matching pattern
  • !!:s/find/replace - last command, substitute find with replace

More info on command history

Solution 4 - Linux

In the command-line, you can press alt+. or esc-.

It cycles through the last argument of your previous commands.

Solution 5 - Linux

If you know the number given in the history for a particular command, you can pretty much take any argument in that command using following terms.

Use following to take the second argument from the third command in the history,

!3:2

Use following to take the third argument from the fifth last command in the history,

!-5:3

Using a minus sign, you ask it to traverse from the last command of the history.

Solution 6 - Linux

!* runs a new command with all previous arguments.

ls /tmp
cd !*
#you are now in /tmp

Solution 7 - Linux

Yes, you can use !$ to recall the last argument of the preceding command.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe CoderView Question on Stackoverflow
Solution 1 - LinuxcodaddictView Answer on Stackoverflow
Solution 2 - LinuxRobert GowlandView Answer on Stackoverflow
Solution 3 - LinuxJohntronView Answer on Stackoverflow
Solution 4 - LinuxAntonio ManoView Answer on Stackoverflow
Solution 5 - LinuxMadiszView Answer on Stackoverflow
Solution 6 - Linuxuser6768257View Answer on Stackoverflow
Solution 7 - LinuxJustin EthierView Answer on Stackoverflow