Explaining Variable Substitution in Bash

The aim of this page📝 is to share notes on variable substitution in Bash, annotating the wonderful Advanced Bash-Scripting Guide > Variable Substitution

Carefully distinguish between name and value

a=375
^^^^^^^^assign a value to a symbol
hello=$a
^^^^^^^^evaluate a symbol $a and apply the assignment operation to another symbol hello

There are ~5 exceptional situations when even a variable shows up without $ (a sigil)

Etymologically, the sigil is taken from magic

There are 3 multiple ways to perform the assignment

The $variable form is in fact syntactic sugar

${variable}

It is essential to differentiate between strong (single) and weak (double) quoting

It is a big difference to use and not using strong quoting for variable expansion

>>> hello="A B  C   D"
>>> echo $hello
A B C D
>>> echo ${hello}
A B C D
>>> echo "${hello}"
A B C D

It is permissible to set multiple variables on the same line

var1=21 var2=22 var3=23

Setting the variable to null is not the same as unsetting it

>>> hello=
>>> echo "\$hello (null value) = $hello"
$hello (null value) =
>>> uninitialized_variable=23    #set it
>>> unset uninitialized_variable #unset
>>> echo "uninitialized_variable = $uninitialized_variable"

uninitialized_variable =

LINKS

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com