More on bash history

Bash provides a powerful history system that helps you in repeating commands and arguments.

For example, the !! command, repeats the last executed command.

If you want to execute a command typed before the last one, you can select it with the following:


Something like this:

$ ls
$ ps
$ !-2

The last command executes ls again.

In addition, you can specify previous arguments too. This is done with the !:n command (n being a number). Let’s see an example:

$ less file.txt
$ cp !:1 file_copy.txt

The last command takes the first argument of the previous executed command and makes a copy with a different name.

If this is not enough for you, you can select a certain parameter of an arbitrary previously executed command. In order to do this, you have to join the two command we have seen so far.

$ ls file1.txt file2.txt
$ ps
$ echo !-2:1

This prints file

Have fun!


  • On 06.17.08 Pedro said:


    Why not including the following:

    $ ^Foo^bar

    searches for ‘Foo’ and changes it to ‘bar’ *in the last executed line*. For example:

    $ for i in * ; do ls -l $j ; done
    [ notice the mistake, ‘$j’ for ‘$i’ ]

    $ ^$j^$i

    runs ok.

    Just a suggestion.

    Thanks for the nice post.

  • On 02.18.09 commandliners » Alias said:

    […] can help you saving a lot of time by avoiding repetitive and long commands and […]

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields