Special Variables

The locations at the command prompt of the arguments as well as the location of the command, or the script itself, are also stored in corresponding variables, along with a number of other special system set variables, as follows:

 

  • $0 - The name of the Bash script
  • $1 - $9 - The first 9 arguments to the Bash script
  • $# - How many arguments were passed to the Bash script
  • $* - All arguments supplied to the Bash script
    • takes the entire list as one argument with spaces between
  • $@ - All arguments supplied to the Bash script
    • takes the entire list and separates it into separate arguments
  • $? - Exit status (/return value) of the most recently run process
  • $$ - PID (Process ID) of the current script
  • $USER - Username of the user running the script
  • $HOSTNAME - Hostname of the machine the script is running on
  • $SECONDS - Number of seconds since the script was started
  • $RANDOM - Returns a different random number each time is it referred to
  • $LINENO - Returns the current line number in the Bash script

 

Note: the $* special parameter takes the entire list as one argument with spaces between and the $@ special parameter takes the entire list and separates it into separate arguments.

 

 

Invoke:

sh specialVars.sh Derrick Ducati Electronics

 

Output:

The name of this script is: specialVars.sh
3 arguments were used
The passed in arguments were: Derrick and Ducati and Electronics
The user running this script is: derrick
The hostname of this computer is: xps13
It has been 6 seconds since this script was started
The current line giving this output is 10
Here's a random number 4130
All the arguments were: Derrick Ducati Electronics
And again using a different special variable: Derrick Ducati Electronics
The PID of this script is 31360
The exit code of this script is 0