Special Variables in Bash Explained [With Examples]
Abstract: the last value "i" will be present in the $9 variable. 2.3. $# - Number of Arguments To get the count of arguments we generally would use loops. We it
In Bash, special variables are those variables that are intentionally set by the shell internally so that it is available to the user. These variables are also referred to as special parameters. Special variables are mainly assigned with the task of storing information related to the shell or the environment. They are ideal when it comes to writing Bash scripts because their role is to provide access and manipulate important information about the executing shell or the script.
2. List and Explanation of Special Variables in BashThe following table gives a quick overview of 9 special variables in Bash.
Special VariablesDescription$0The filename of the current script.$1…$9Positional parameters storing the names of the first 9 arguments$$The process id of the current shell.$#The number of arguments supplied to a script.$*Stores all the command line arguments.[email protected]Stores the list of arguments as an array.$?Specifies the exit status of the last command or the most recent execution process.$!Shows the id of the last background command.$-Shows the options set used in the current bash shell. 2.1. $0 - The Name of the ScriptThe special Bash variable $0 is meant to hold the name of the script. Let us try an example:
Example:
#!/bin/bash echo "I am running the script $0 "
We have a simple script that displays the name of the file when executed
2.2. $1 to $9 - Arguments to the ScriptWe can refer to the arguments passed to the script by using the special variables $1 to $9.
Example:
#!/bin/bash echo argument 1 is $1 echo argument 2 is $2 echo argument 3 is $3 echo argument 9 is $9
Run this script as:
./splVar2.sh a b c d e f g h i
The $0 stores the name of the script. $1 holds the first argument which is "a" and so on. Thus, the last value "i" will be present in the $9 variable.
2.3. $# - Number of ArgumentsTo get the count of arguments we generally would use loops. We iterate over all the arguments passed to the script and increment the count by 1 every time. Instead of that, we just need to employ the $# variable.