Coder Perfect

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

Problem

Is there a way to remember the preceding command’s parameter in Bash?

I normally start with vi file.c and then gcc file.c.

Is there a way to remember the preceding command’s parameter in Bash?

Asked by The Coder

Solution #1

To recall the last parameter of the previous command, use $ or!$.

You can also use Alt +. to remember the last argument of any previous command.

Answered by codaddict

Solution #2

If the command before it had two arguments, such as this,

ls a.txt b.txt

You could put “first” if you wanted the first one.

!:1

giving

a.txt

You could also type both if you wanted.

!:1-2

giving

a.txt b.txt

This can be extended to any number of arguments, for example:

!:10-12

Answered by Robert Gowland

Solution #3

!!:n, where n is the desired argument’s 0-based position.

For example:

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

echo !!:2
# "two"

Previous commands are accessed using the! prefix.

Other useful commands:

More information on the history of commands

Answered by Johntron

Solution #4

You can use the command-line shortcuts alt+. or esc-.

It repeats the final parameter of each of your previous commands.

Answered by Antonio Mano

Solution #5

You can pretty much take any argument in a command using the following phrases if you know the number supplied in the history for that command.

To get the second parameter from the third command in the history, do the following:

!3:2

To get the third parameter from the fifth last command in the history, do the following:

!-5:3

You tell it to go back to the last command in the history by using a negative sign.

Answered by Madisz

Post is based on https://stackoverflow.com/questions/3371294/how-can-i-recall-the-argument-of-the-previous-bash-command