PreshBlog

Bash’s $_ variable (last argument)

by on Jul.07, 2007, under Linux, System Administration

A few weeks ago, I found out about the incredibly useful Bash variable $_, which means “the last argument of the last command executed”.

It’s kind of similar to Perl’s $_ var in some ways, and can save a lot of typing.

Here’s an example of it in use:


[davidp@supernova:~]$ ls -l /var/log/apache/access_log
-rw-r--r-- 1 root root 33771565 2007-07-04 07:48 /var/log/apache/access_log
[davidp@supernova:~]$ echo $_
/var/log/apache/access_log

Notice that when I echo’d $_, it contained the last argument of the previous command.

Now for a more useful, real-world example – changing ownership and permissions on a file:


chown davidp:users /some/long/path/file && chmod g+rx $_

Using $_ in the chmod command saved a good bit of typing – obviously the $_ will contain the path to the file we’re talking about, as it was the last argument to the previous command.


2 Comments for this entry

  • Qeny

    If you’re using bash interactively, then you can just use alt+. (alt+period) to “type” the last arg of the last command.

  • $USER

    The same thing applies to !$. As in:
    $ mkdir /very/very/very/very/long/filepath
    $ cd !$
    Those keys are just easier for me to reach. Preference I guess. :)

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!