Bash – How to repeat a command with an added parameter

bashcommand history

I know how to repeat a command and add more text after it with !! like so:

ls -l
!! tmp

The second line expands to ls -l tmp.

But what if I wanted to add parameters to the command in between the words? For example if I've done the following:

ls tmp

…then I would often want to add the -l parameter to the command but not retype the whole thing or press up and use arrow keys to set the cursor to the correct place. !! -l doesn't work because it becomes ls tmp -l which is not valid. (In practice the command is much longer than the simple example I've used here.)

In other words I'm looking for something like ?? -l where ?? is something that repeats the previous command but adds -l in between the first and second words.


Just to make it clear, ls -l tmp is just a simplified example. The real-life use case is closer to something like /very/long/path/to/very-long-command --with=a --very=long --parameter=list.

Best Answer

!!:0 is the 0'th word of the previous command, and !!:* is all the words except the 0'th.

!!:0 -l !!:*

is the command you're looking for.

Source https://www.gnu.org/software/bash/manual/bash.html#Word-Designators