Variables in bash are a bit complex from time to time and there are lots of conditions to take into account but I've tried to outline the most important parts below. An important thing to keep in mind is that variables in bash are always assigned and interpreted as strings.
Assigning a variable in bash is very simple. You define the name for your variable and your data to go into the variable. It is common use to write variables that are globally scoped (more on this in a moment) in uppercase, but this is not required:
MY_VARIABLE="Some string"
MY_BOOL=true # -> assigned as: "true"
CURR_PATH=$PWD # You can reassign variables with other variables
# Reassigning MY_BOOL as false.
MY_BOOL=false
Variables in bash are called by prefixing the variable name with the $ symbol. It is important to always wrap variable calls in quotes so that there are no issues with path names containing a space for example. We will see more on this issue later on in the course.
MY_VARIABLE="Some string"
echo "$MY_VARIABLE" # "Some string"
# This also works but is considered unsafe.
echo $MY_VARIABLE # "Some string"
Variables can also be interpolated or concatenated with other variables or strings:
ROOTPATH="/home/thibmaek/development"
echo "$ROOTPATH/my_project" # "/home/thibmaek/development/my_project"
Since regular variables in bash can be reassigned at any point in your code, there must also be a way to stop this from happening for variables you don't want to be reassignable. You can create read only variables (constants) to block reassignments:
readonly MY_VAR=true
MY_VAR=false # bash: MY_VAR: readonly variable
echo "$MY_VAR" # true
Variables can only be scoped inside function blocks. It is good practice to unset them just before the function block exits.
Scoping may be less important in bash than in other languages but it is good practice to scope variables in lengthy scripts to make sure you don't accidentally call or reassign them outside of the script or in other functions.
# Example using scoped variables
function fn() {
local name=Thibault
declare -i job=Developer # Using declare to create a var in function block makes it scoped by default
echo "Hi from $name who is a $job"
}
fn # "Hi from Thibault"'
echo "$name" # No output, exits with 0
# Example using 'global' variables
function fn() {
# Global assign for the complete scope of this script
name=Thibault
echo "Hi from $name"
}
fn # "Hi from Thibault"
echo "$name" # "Thibault"
There is a special type of variables called environment variables (or envs for short). These kind of variables are defined on the shell itself and are accessible in every script called with/in this shell. They can thus be seen as superglobals (like window
in JS). You can inspect all env vars with the printenv
or env
command.