My Favorite Unix Trick

Yesterday I saw this interesting tweet from @markbates:


My favorite command is this little guy:


This simply executes the most recent command. This is especially useful if you typed a command but left out a qualifier, for example if you typed

vi /etc/hosts

and you realize that you needed to run this as admin, you can simply do:

sudo !!

This is really just scratching the surface of how you can access the history in bash. For starters, you can type history to see the last 600 commands you typed. You can also do Ctrl+R to search for a command you typed (instead of pressing Up 50 times).

The !! trick is actually just a specific version of the more generic !N command. It’s very easy to specify any of your most recent commands.

  • !-N will substitute the Nth most recent command – e.g. !-1 will substitute the most recent command, !-2 the second most recent, etc.
  • !! is shorthand for !-1, to quickly substitute the last command.
  • !string will substitute the most recent command that begins with string.
  • !?string? will substitute the most recent command that contains string.

You can even specify only a certain argument in the previous command, for example !!:1 will get the first argument of the previous command.

Happy coding.