Built-in Shell Variables (and Arrays)
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.
$!
- The process ID of the most recent background process.
BASH
- The full path used to invoke this instance of Bash.
BASH_REMATCH
-
This is actually an indexed array, not a variable.
If a [[ "${string}" =~ ${regex} ]] statement is true (i.e. when the ${regex} matches the ${string} ), then BASH_REMATCH[0] contains the entire matched substring and the BASH_REMATCH[n] contain the matched sections from the left to the right, from number 1 to n.
See also: Regular Expressions.
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:
if (( $(bash -c 'echo ${BASH_VERSION%%.*}') >= 4 )); then
echo "yes"
else
echo "no"
fi
- To verify if Bash is at least of version 3.2:
if printf '%s\n%s\n' "$BASH_VERSION" "3.2" | sort -rVC; then
echo "yes"
else
echo "no"
fi
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.
2022-02-12
|