Helpful shell shortcuts

So this may be a little basic, but I find myself using these two shortcuts quite a bit while at the shell.

If you ever find yourself wanting to “reuse” the last argument in a command — for example, here I move a file from one location into /var/tmp and I want to “cd” into /var/tmp without having to type it, use the shell variable !$…

locutus:~
(svoboda)> dd if=/dev/zero of=/tmp/blah bs=1024000 count=1
1+0 records in
1+0 records out
1024000 bytes (1.0 MB) copied, 0.0109023 s, 93.9 MB/s

locutus:~
(svoboda)> mv /tmp/blah /var/tmp

locutus:~
(svoboda)> cd !$
cd /var/tmp

locutus:/var/tmp
(svoboda)> pwd
/var/tmp

If you wanted to “preface” your last command, you can throw anything you want into the shell followed by the !! shell shortcut.
locutus:/var/tmp
(svoboda)> “Armin van Buuren’s a State of Trance”
-bash: Armin van Buuren’s a State of Trance: command not found

locutus:/var/tmp
(svoboda)> echo !!
echo “Armin van Buuren’s a State of Trance”
Armin van Buuren’s a State of Trance

The first line mearly “shows” what is being executed, with the second line executing the actual command.  Not rocket science, but whatever helps on saving keystrokes!

4 thoughts on “Helpful shell shortcuts”

  1. Here are a few I use constantly that expand on this post. In true regex fashion, !^ is the first argument of the previous command just like !$ is the last argument of the previous command. Going even further, !:X will expand to argument X where X is a number.

    Example:
    $ echo 1 2 3 4 5
    1 2 3 4 5
    $ echo !^
    1
    $ echo 1 2 3 4 5
    1 2 3 4 5
    $ echo !:3
    3

    Take a look at bash(1) and search for “Event Designators”.

Leave a Reply

Your email address will not be published. Required fields are marked *