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

Pavol Kutaj
2 min readNov 18, 2022

Carefully distinguish between name and value

  • bash is explicit about the distinction of the signifier and signified, about symbol and meaning
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)

  1. when declared/assigned
  2. when unset
  3. when exported
  4. in the arithmetic expression
  5. when used as a signal

Etymologically, the sigil is taken from magic

The use of symbols for magical or cultic purposes has been widespread since at least the Neolithic era. The term sigil derives from the Latin sigillum (pl. sigilla or sigils), meaning “seal.”

There are 3 multiple ways to perform the assignment

  1. typical with the assignment operator var1=42
  2. in a read statement
  3. at a head of a loop (for var1 in 1 2 3)

The $variable form is in fact syntactic sugar

  • The full form is
${variable}
  • with {} being a special character for the inline group
  • {} is the form where the content of brackets is treated as if they were a single command
  • with $ being a special character for expansion
  • there’re 3 expansions: 1)parameter 2)command 3)arithmetic
  • the expansion could be a synonym for evaluation, perhaps

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

  • Enclosing a referenced value in double quotes (“ … “) does not interfere with variable substitution
  • Using single quotes (‘ … ‘) causes the variable name to be used literally, and no substitution will take place.

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
  • The first code looks like “print the first argument”.
  • It’s actually
  1. Split the first argument by IFS (spaces, tabs, and line feed).
  2. Expand each of them as if it was a glob.
  3. Join all the resulting strings and filenames with spaces.
  4. Print the result.

It is permissible to set multiple variables on the same line

  • you need to separate it by white space
  • NOTE: legibility is reduced and may not be portable
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) =
  • Although the end result is the same
  • unsetting the variable is done with the unset command
>>> uninitialized_variable=23    #set it
>>> unset uninitialized_variable #unset
>>> echo "uninitialized_variable = $uninitialized_variable"

uninitialized_variable =

LINKS

--

--

No responses yet