Bash – Is it possible to replace/change an argument using bash bang (!) and history

bashcommand history

I am currently swooning over the history and ! based featured for bash in Linux.

I am getting used to using !! and !:<argc> and similar features, but is there someway where for instance if I make a mistake by adding a wrong argument previously and then I could remove that false argument and use the command line again.

Example

If I make a mistake like the following:

      mv -r movableFolder/ targetFolder/

since there is no -r option for mv, I would like to remove it using some ! trickery to make it :

      mv movableFolder/ targetFolder/

I know I can do from the above history command:

     mv !:2 !:3

but is there anyway to substitute mv with a ! command?

Best Answer

Hoho, I am glad there is still someone who is interested in this ancient feature. I still use it, but most of the time I find myself using up-arrow to recall past commands.

Twenty-five years ago I had \! as a component of my PS1 to be able to number past commands and recall them like !54. I don’t remember when I decided that it wasn’t useful any more... Now I use !!, !-2, !-3 and above all !$ and !$:h often, but not much more.

Anyway, you seem to ask two different things:

  • Correct previous command:

    $ mv -r from to
    $ !!:s/-r//
    mv  from to
    

!:s/-r// can be used instead of !!:s/-r//. The s/<string>/<replacement>/ modifier replaces the first occurrence of <string> with <replacement>.

  • Address command name

    $ mv from to
    $ echo !:0
    mv