Shell Script – The Importance of Adding Quotes to Variable

Example 1 :

#!/bin/sh

TITLE="The Magic Land"
if [ $TITLE == "The Magic Ocean" ]; then
   echo "OK"
fi

If you run the above script, you will receive this error message :

root@ubuntu:~# ./example1.sh
 ./example1.sh: 4: [: The: unexpected operator
 root@ubuntu:~#

The reason is variable $TITLE automatically expands in the if section :

if [ The Magic Land == "The Magic Ocean" ]; then

The fix is easy, just enclose variable $TITLE in quotes

#!/bin/sh

TITLE="The Magic Land"
if [ "$TITLE" == "The Magic Ocean" ]; then
   echo "OK"
fi

comments powered by Disqus