Special Variables in Linux $0 $? $$ $#
An important feature of shell scripts is the possibility of confirming execution with success of a given command.
Special return variables
It’s called a return variable.
The return variable is filled every time a command is executed. If the value returned is 0, the command was successfully executed.
If the value is different from 0, a problem was encountered.
If used in scripts, its value must be verified immediately after the execution of the desired command.
**Variable** | ****What is for**** |
$# | Returns the number of arguments the program received. |
$\_ | The underscore contains the absolute name of the shell file or script that is being executed as passed in the argument list. |
$? | Return variable when a program terminates execution. |
$$ | Provides the PID of the Shell process. |
$! | Provides the PID of the last program running in the background. |
$0 | Returns the name of the program executed. |
$n | returns the program's **n-number** argument. |
$\* $@ | Returns all arguments entered when running the program. |
Take a look at the sample script where these variables are used:
When executed, it will produce the following result:
Variable $?
The variable $? represents the exit status of the previous command.
Example:
In this example the variable $? It will show the return code from the previous command echo “Will join”.
It has been agreed that when a command is executed without errors, it will return the return code 0 (zero). When there is an error, a value greater than 1 will be returned, and depending on the value, the command developer may provide a list of error codes and their meanings.
Variable $!
The variable $! will return the process ID of the last background command:
Don’t confuse it with the variable $$
Variable $$
The $$ variable shows the current shell process ID. For shell scripts, this is the ID of the process in which they are running:
Variable $#
The $# variable returns the number of arguments the program received. It can be used in scripts when you want to know if the number of arguments required has been satisfied.
Using { }
Keys can be used to highlight to the shell a variable that is used “inside” a text. See the example:
Difference between $* and $@
- $* and $@ when used outside of double quotes are identical and expand to the arguments.
- “$*” in quotes returns all arguments as if they were a single result separated by a space. Arguments “One two” “three” will return “one two three”, breaking the spaces between the arguments, as if they were three arguments and not two.
- “$@” will return the arguments exactly as they were received. “One two” “three” will return as two arguments “One two” “three” without breaking the spaces.
Conclusion
If you’re writing a shell script, it’s very important that you know the special variables.