Sep 22 2009

Linux Bang Commands

If you spend a lot of time on the linux command line you quickly find that it requires a lot of typing and retyping commands. I used to find myself using the exact same lengthy command multiple times a day and to get there I would type “history | grep some_command” and then execute it from there. Since I knew enough to get the job done I hadn’t really tried to find more efficient ways of doing the same old thing. But when I found out about the Linux bang (!) commands I realized how wasteful what I was doing really was.

The exclamation mark, in this case, is referred to as a ‘bang’.

  • !!
    This bang command, when entered into the bash shell will run the previous command. It basically does the same thing as hitting the up arrow to take you to the previous command and then hitting enter.
     
  • !ls
    This will run the last command that started with ‘ls’. If you ran ‘ls -al /etc/init.d’ a few commands ago and then you type ‘!ls’ the full command will be run again, assuming that you haven’t used that command since then.
     
  • !ls:p
    This will display the command instead of running it.
     
  • !$
    This one will run the last word of the previous command. This one is mainly useful for substitutions.
     
  • !$:p
    Instead of running the last word of the previous command this will print it out.
     
  • !*
    This bang command will run the previous command without the first word. This one is also only really useful for substitutions as we see in the examples that follow.
     
  • !*:p
    This will print the previous command without the first word.
     

Here are a few examples of how to use these bash bang commands in everyday command line usage :

For the purposes of these examples, every example will assume these are the last three commands you ran:


    % which firefox
    % make
    % ./foo -f foo.conf
    % vi foo.c bar.c

Getting stuff from the last command:

    Full line:     % !!            becomes:   % vi foo.c bar.c
    Last arg :     % svn ci !$     becomes:   % svn ci bar.c
    All args :     % svn ci !*     becomes:   % svn ci foo.c bar.c
    First arg:     % svn ci !!:1   becomes:   % svn ci foo.c

Accessing commandlines by pattern:

    Full line:     % !./f          becomes:   % ./foo -f foo.conf
    Full line:     % vi `!whi`     becomes:   % vi `which firefox`
    Last arg :     % vi !./f:$     becomes:   % vi foo.conf
    All args :     % ./bar !./f:*  becomes:   % ./bar -f foo.conf
    First arg:     % svn ci !vi:1  becomes:   % svn ci foo.c

I found those examples here.

Share