UNIX/Linux systems have special variables that are used internally by the shell and are available to all users.
Input to the bash script is provided in the following format:
./script.sh <input list>
Special Variable | Description |
$0 | The filename of the current script. |
$n | "n" refers to a positive number that represents the nth argument passed to the script. For example, $1 represents the first argument. |
$# | Represents the number of arguments passed to the script. |
$* | Represents all the arguments passed to the script. |
$? | Returns the exit status of the last command that was executed. |
$! | Holds the process ID of the last background command. |
$$ | Represents the process ID of the current shell. For shell scripts, this is the process ID under which the scripts run. |
$@ | Represents all the arguments passed to the script. |
The following bash script demonstrates these special variables and their usage. All scripts are run using the command ./script.sh This is the argument list
.
#!/bin/bashecho "Script name $0"for ARGS in $@dolet i=i+1echo "Argument $i is $ARGS"doneecho "Parameter list: (individually) $@"echo "Parameter list: (as a single list) $*"echo "Total number of parameters $#"echo "Process ID $$"
These two variables hold the complete parameter list. The difference between them is that $@
holds each parameter individually, while $*
holds all parameters as a single list of words separated by spaces.
#!/bin/bashecho "Using \$*..."for ARGS in "$*"dolet i=i+1echo "Argument $i is $ARGS"doneecho -e "\nUsing \$@..."for ARGS in "$@"dolet i=i+1echo "Argument $i is $ARGS"done
The exit status of a command is a numerical value that is returned after the execution of the command. This numerical value indicates whether the command was executed successfully or not. Moreover, exit status can indicate different types of errors thrown in case the command was not executed successfully. As a rule of thumb, an exit status of indicates success, and an exit status of indicates failure.
echo "Executing echo command..."if [ $? -eq '0' ]thenecho "The last command executed successfully: Exit status $?"elseecho "The last command was unsuccessful: Exit status $?"fi
Free Resources