1

Is it wrong to use single quotes to enclose different strings/integers while comparing them ?

I've used both single quote and double quote together in a script, most of the time they works, but there must be rule to maintain script consistency.

So which quote should I use in which portion and why ?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Arnab
  • 1,581
  • Related: http://unix.stackexchange.com/q/189073/135943 http://unix.stackexchange.com/q/16303/135943 – Wildcard Nov 17 '16 at 21:58

1 Answers1

1

Some things you want to take notice when choosing whether to use single or double quotes in comparisons:

Should expansions work?

Single quotes basically mean you want the literal value of the string. So they are not really useful on most cases where you want to do comparisons, since usually you will want to compare variables. Comparing '$variable1' and '$variable2' will result false everytime, since you will be comparing the literal strings and not the variable values.

Double quotes still allow some expansions to happen (check the "Quoting" section of man bash page for more details). In the example above, "$variable1" and "$variable2" will actually expand to the values contained in the variables, which will then be compared.

Be aware of empty strings!

When using test to compare the value of strings, be aware that expanding an empty string without enclosing double quotes can result in syntax errors. For example, the following code would work and induce you to think it's bug free:

str="STRING"
if [ $str = "STRING" ]; then
    echo "EQUAL"
fi

But then, if at some point you had an empty string bash would complain about expecting a unary operator. That's because the code would expand to:

str=""
if [ = "STRING" ]; then
    echo "EQUAL"
fi

And = is not a unary operator, even though it has only one parameter after it. To avoid this, use a double quote around the variable name in the comparison like this:

str="STRING"
if [ "$str" = "STRING" ]; then
    echo "EQUAL"
fi

There are other things to keep in mind when picking quotes (like escaping some special characters - $, `, \, and ! when history expansion is enabled - on double quotes), but basically, if you want a literal string use single quotes. When you need some expansions to work use double quotes. You can also mix them if you want (this avoids some escaping):

hello='Hello World'
mystring="$hello"'!'
echo "$mystring"
IanC
  • 850