2.2 Variables
Like most programming languages, Bash supports the ability to introduce user-defined variables. These can be used for storing data for retrieval at a later point, or for use in later computations.
Variables can be set in Bash in a number of ways, either explicitly or by simple assignment:
# Set via simple assignment
EXAMPLE_A="test set simple assignment"
# Set via explicit assignment
export EXAMPLE_B="test set explicit"
echo "${EXAMPLE_A} / ${EXAMPLE_B}"
Please note that you should not add spaces around the equals operator when assigning variables, as Bash will attempt to process the script differently and will likely error out.
Variable Scoping
By default, variables in Bash are scoped globally; meaning anything defined is available for reading and writing everywhere after being defined. This behavior can be useful, but may not always be desired.
In the case of functions, variables can instead be defined locally using the local
keyword.
EXAMPLE="This was defineed globally"
function test() {
local EXAMPLE="This was defined locally"
# This will print the local declaration
echo $EXAMPLE
}
# Prints local declaration
test
# This will print the original declaration
echo $EXAMPLE
System Variables
In addition to the ability to define custom variables, Bash provides a variety of system-defined constants which can be used to determine how the script should behave under certain conditions. Below is a subset of some of the variables you can use.
Variable | Description |
---|---|
SHELL | The name of the shell used |
PWD | The current working directory |
HOME | The home directory of the current user |
SHLVL | The number shells the current shell is running on top of (terminal nesting depth) |
PATH | The directories to search for bash commands |
User Arguments
Arguments can also be provided to your script and can be referenced using positional numeric arguments $1
through $9
. You can reference numeric arguments higher than this, but it will require wrapping the number in curly braces like so: ${10}
If you would like to get all arguments provided to a script, you can use either $@
or "$@"
variables to retrieve them all at once. It is recommended to use the latter format however if you intend for quoted strings to be parsed as a single argument rather than multiple.