Wednesday, May 6, 2009

Unix Bang and Bang Bang shortcuts


The Unix Bash shell is an incredibly powerful tool. It even has built in shortcuts to make your life easier. One of these such shortcuts is called bang. The bang shortcut is executed using the exclamation point character (!). Bang is used to search backward through your Bash history until it finds a command that matches the string that follows it and executed it. For example:
!cat
This will search backward through your history until it finds a use of the cat command. It will then execute that command that uses cat. This can be useful if it was a long command and you don't want to retype it. To get a look at your history, use the history command:
history
Bang also has a feature to let you check the command it finds before executing it. Use this syntax instead:
!cat:p
Now bang will search back through your history for the use of the cat command like before, but instead of executing that command, it will print the command for you to look at. That's not all though, it will also copy that command it found to the end of your history. This is useful because if you do want to execute that command you can now use the bang bang shortcut to run it.

When a command with the bang bang shortcut is executed, the bang bang characters are replaced with the last command from the history. For example:
!cat:p
!!
This will search for the the recent appearance of the cat command, print that command to the console, and copy that command to the end of the history. The bang bang command will then run that command containing cat. Bang bang can also be used with other Bash tools, like pipe and grep, for example:
!cat:p
!! | grep "hello"
Here, the most recent command containing cat is printed and copied to the end of your history. Then, that command is executed with its results being piped into the grep command, which has been specified to print those lines containing the string "hello".

By far my favorite use of the bang bang is a trick that's been used by command line junkies for years. This is the sudo bang bang shortcut. Ever run a command only to have it fail for lack of superuser privileges? Instead of retyping the whole command with sudo or even pressing the up arrow and scrolling back to the beginning of the command to type sudo, you can just type this:
sudo !!
I hope you find these tricks useful.

The image above comes from here.

2 comments:

  1. Best explanation of bang I have found! Thank you.

    ReplyDelete
  2. Thanks for this. Best definition and use cases for bang I've yet found.

    ReplyDelete