Meaning/usage of $_ in bash

VirginSnow at vfemail.net VirginSnow at vfemail.net
Wed Jul 23 13:16:54 EDT 2008


> From: "Michael ODonnell" <michael.odonnell at comcast.net>
> Date: Wed, 23 Jul 2008 12:57:14 -0400

>  "When bash invokes an external command, the variable $_ is set to
>   the full file name of the command and passed to that command in its
>   environment."

> ...which seems to describe one piece of how it actually works in one
> situation.  For example, if I create and execute a shell script thus:

Right.  The "other situation" is when bash executes a command
internally (without invoking an external command).  In this case, bash
sets _ to the the last token on the last command line (the last
parameter in the command, if it has any, or the command name, if the
command had no parameters).

So:

  $ date > /dev/null
  $ echo $_
  date
  $ date -d now > /dev/null
  $ echo $_
  now

I tend to use $_ as a shortcut when doing a mkdir/cd combo:

  $ mkdir -p /tmp/foo/some-really-long-name-i-dont-feel-like-typing-again
  $ cd $_
  $ pwd
  /tmp/some-really-long-name-i-dont-feel-like-typing-again


More information about the gnhlug-discuss mailing list