Back

Use Double Quotes When Using Variables in Bash

Earlier I was experimenting with bash scripting, revising it again from w3schools as you'll be able to find on here.

It was operators section and I was reading through different operators and their purposes. Earlier I saw an example of assosiative arrays(yea, the one's like dictionary) so I thought of creating associative arrays of these different types of operators and printing them on my shell.

I wrote this code (also, given below).

#!/bin/bash

# comparison operators
echo "comparison operators"
declare -A comparison_operators
comparison_operators["equal_to"]='-eq'
comparison_operators["not_equal_to"]='-ne'
comparison_operators["less_than"]='-lt'
comparison_operators["less_than_or_equal_to"]='-le'
comparison_operators["greater_than"]='-gt'
comparison_operators["greater_than_or_equal_to"]='-ge'

for i in ${comparison_operators[@]}; do
  echo $i
done

# string operators
echo "string operators"
declare -A string_operators
string_operators["equal_to"]='='
string_operators["not_equal_to"]='!='
string_operators["less_than"]='<'
string_operators["greater_than"]='>'

for i in ${string_operators[@]}; do
  echo $i
done

# arithmetic operators
echo "arithmetic operators"
declare -A arithmetic_operators
arithmetic_operators["addition"]='+'
arithmetic_operators["subtraction"]='-'
arithmetic_operators["multiplication"]='*'
arithmetic_operators["division"]='/'
arithmetic_operators["modulus"]='%'

for i in ${arithmetic_operators[@]}; do
  echo $i
done

On executing, I was getting this response.

comparison operators
-le
-gt
-eq
-ge
-lt
string operators
>
!==
==
<
arithmetic operators
%
/
+
-
data-types
operations
operators
README.md
variable

Why are all the files/directories being listed right after the arithmetic_operators? Weird, right?

Can you spot the bug?

Well, the problem was I did not use double quotes around the variable names in the for loop, these lines and hence globbing occured with path expansion.

for i in ${arithmetic_operators[@]}; do
  echo $i

When the array element was * in the for loop, for arithmetic_operators["multiplication"]='*', bash expanded it into all files and directories inside the current working directory and hence printed all the file/directory names.

On using double quotes the issue was resolved.

- for i in ${arithmetic_operators[@]}; do
-   echo $i
+ for i in "${arithmetic_operators[@]}"; do
+  echo "$i"

Fun fact: My IDE linter was telling me to use double quotes around variable names

Now, you know how important it is to use double quotes around variable names in bash to avoid globbing or word splitting.