Built-in Shell Variables

The $ sign is actually not part of the variable name, although some built-in variables are always referenced this way. We do the same.

$0
The first element passed to the shell is the command name.
$n
The nth argument passed on the command line. If n ≥ 10, then the syntax must be ${n}.
$*
All the arguments on the command line. The values are separated by the first character in the shell variable IFS: (${1} … ${n}). See also: the IFS entry in Other Shell Variables.
$@
All the arguments on the command line. The values are individually quoted: ("${1}" … "${n}").
$#
The number of command-line arguments.
$?
The exit value of the last executed command.
$_
The last argument of the previous command.

BASH
The full path used to invoke this instance of Bash.
BASH_VERSION

A string describing the Bash version.

Examples of use:

  • If more than one version of Bash are installed on the computer, then the running one can be retrieved by:
    bash -c 'echo $BASH_VERSION'
  • To prompt only the numeric «major.minor.patch» part of the version string:
    echo ${BASH_VERSION%%[^0-9.]*}
  • To verify if the running Bash is at least version 4:
    (( $(bash -c 'echo ${BASH_VERSION%%.*}') >= 4 )) && echo "yes" || echo "no"
HOSTNAME
The name of the current host.
MAPFILE
The default array for the built-in mapfile and readarray commands.
OPTARG
The value of arguments to last option processed by the built-in getopts command.
OPTIND
The numerical index of OPTARG in a built-in getopts command.
PWD
The current working directory («print working directory»). It can be changed by the built-in cd command.

2020–07–19