Bash – Why use double quotes in a [[ ]] test

bashquotingshelltestvariable

Let's say we have 2 integers in a bash script:

value1=5
value2=3

Then why do we need to use double quotes in case of a test ? For example:

if [[ "$value1" -eq "$value2" ]]

Why not just use the following ?

if [[ $value1 -eq $value2 ]]

To me, the double quotes don't make any sense.

Best Answer

Word splitting.

This example is very improbable, but possible, so if you want to code defensively, cover your tracks with quotes:

$ set -x
$ value1=5
+ value1=5
$ value2=3
+ value2=3
$ [ $value1 -eq $value2 ]
+ '[' 5 -eq 3 ']'

OK, all good so far. Let's throw the wrench into the gears:

$ IFS=456
+ IFS=456
$ [ $value1 -eq $value2 ]
+ '[' '' -eq 3 ']'
bash: [: : integer expression expected

Oops.

$ [ "$value1" -eq "$value2" ]
+ '[' 5 -eq 3 ']'

Ahh.

Related Question