Re-Run the Last Command While Replacing Syntax or Typos

Jun 13, 2012 - 6 Comments

If you’ve ever entered a lengthy command into the terminal and upon execution discovered a syntax error, a “no such file or directory”, or “command not found” message because you made a typo, you’ll love this quick tip that lets you rerun the last executed command while replacing the erroneous syntax. You’ll need to be using the default bash shell for this to work.

The general syntax to use is as follows:


!! runs the last command again, while :gs/old/new replaces instances of the text “old” with “new” within the last command.

For example, here’s a simple change directory command with an error in the path:

cd /System/Library/CoerServices/

Notice “CoerServices” should be “CoreServices”, but rather than type out the entire command and path again, you can enter the following:


And suddenly you’re in the proper directory.

This is obviously extremely useful when you’ve discovered errors floating in command line syntax somewhere, but it’s also perfect for toggling settings on and off through things like defaults write commands by replacing “no” with “yes” and so forth:


You can also place sudo in front of !! to run the previous command as root.


Related articles:

Posted by: William Pearson in Command Line, Mac OS, Tips & Tricks


» Comments RSS Feed

  1. Bill says:

    If you get the History Number (i.e. type history) you can change the contents of any previous command by inserting the command number after the first !. As an example if the history command shows that command number 815 is ‘ls -aelF’ and you want to get rid of the e you can type – !815:gs/e//

  2. drdrapp says:

    and ctrl+r is search through command history.

  3. madra says:

    I knew about using the “up arrow” to scroll back through previous commands before, but your “sudo !!” tip is worth the entrance fee alone.

    When I think of the number of times I’ve typed a command, forgetting to “sudo” it first and then had to use “up arrow” to show previous command, then tappy-tappy-tappy on “left arrow” to get the cursor back to the start of the line, to put “sudo” in!


  4. James says:

    You can also use the ^ to replace typos:

    $ la bla
    -bash: la: command not found
    $ ^la^ls

Leave a Reply


Shop on and help support OSXDaily!

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates

Tips & Tricks


iPhone / iPad



Shop on Amazon to help support this site