Bash Special Variables
In Bash, special variables are predefined variables that hold information about the script, the environment, and the arguments passed to the script.
Special variables are helpful in Bash scripting for various purposes such as accessing command-line arguments, referring to the script’s name, and obtaining the exit status of commands.
The following table provides an overview of some common special variables and their uses:
Variable | Description |
$0 | Holds the name of the script itself. It is useful for referencing the script’s name within the script. Example: echo "This script is $0" |
$1, $2, $3… | Hold the positional parameters or arguments passed to the script. $1 holds the first argument, $2 holds the second argument, and so on. Example: echo "First argument: $1" |
$@ | Represents all the positional parameters as separate quoted strings. It is useful for iterating over all arguments passed to the script. Example: for arg in "$@"; do echo "Argument: $arg"; done |
$# | Holds the number of positional parameters or arguments passed to the script. It is useful for determining the number of arguments. Example: echo "Number of arguments: $#" |
$? | Holds the exit status of the last command executed. It is useful for checking the success or failure of a command. Example: if [ $? -eq 0 ]; then echo "Success"; else echo "Failure"; fi |
$$ | Holds the process ID (PID) of the current script. It is useful for uniquely identifying the script’s process. Example: echo "Script PID: $$" |
$! | Holds the PID of the last background command. It is useful for referencing the PID of a background process. Example: echo "Background PID: $!" |
$IFS | Holds the Internal Field Separator, which determines how Bash recognizes word boundaries in strings. It is useful for changing the word-splitting behavior. Example: IFS=',' read -ra array <<< "a,b,c,d"; echo "${array[2]}" |
$LINENO | Holds the current line number in the script. It is useful for debugging and error reporting. Example: echo "Current line number: $LINENO" |
$BASH_VERSION | Holds the version number of the current instance of Bash. It is useful for checking the Bash version. Example: echo "Bash version: $BASH_VERSION" |
Special variables in Bash provide important information and functionality that can be used to customize script behavior, handle command-line arguments, and improve error handling and reporting.