There are myriad implementations of the common UNIX shell. Often these shells are syntactically compatible and the following rules tend to apply when dealing with variables:
- Names must be alphanumeric and may not start with a number.
- Names are case sensitive and conventionally upper-case.
- There may be no whitespace between the variable name, assignment operator and value when a variable is set.
- Variable names begin with the $ character when referred to in read operations; this character is omitted when they are set.
- Variables are scoped within the script they are defined in, unless they are exported.
- Variables may be flagged readonly upon initialization.
- Command substitution assigns the output of commands contained in $() at the time the variable is set.
- Variables may be unset via the unset command.
COMPLEXVAR="A string containing spaces."
readonly ROVAR="This value can not be changed later."
CSVAR=$( ls /var | wc -l )
Special variables dynamically made available at runtime:
- $0 - The name of the script.
- $1 - $9 - The first 9 arguments to the script.
- $# - How many arguments were passed to the script.
- [email protected] - All the arguments supplied to the script.
- $? - The exit status of the most recently run process.
- $$ - The process ID of the current script.
You can see additional variables currently available to you by issuing env or export without arguments at the command line or from inside your script.
Special variables available to BASH scripts:
- $EPOCHSECONDS - Each time this parameter is referenced it expands to the number of seconds since the Unix Epoch. (eg: 1577354438)
- $EPOCHREALTIME - Same as $EPOCHSECONDS but includes microseconds. (eg: 1577354438.788521)
- $SECONDS - Expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment.
- $RANDOM - Each time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator.
- $LINENO - Returns the current line number in the Bash script.
- $MACHTYPE - A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format. (eg: arm-unknown-linux-gnueabihf)
- $OSTYPE - A string describing the operating system Bash is running on. (eg: linux-gnueabihf)
Additional BASH-specific variables can be found at the BASH Reference Manual.
You can find a more in-depth look at variable syntax and example use cases at https://ryanstutorials.net/bash-scripting-tutorial/bash-variables.php.