linuxbashshellexpr

Why are double quotes needed in defining this variable in shell scripting?


Consider this piece of code:

#!/bin/bash +x
echo -n "String: "
read s
n=`expr index $s " "`
if [ $n -gt 0 ]; then
        m=`expr $n - 1`
        echo "Nome: " `expr substr $s 1 $m`
fi

When I run it with the and write "John Smith" in the prompt, I get this error:

./script.sh: line 5: [: -gt: unary operator expected

I can fix it by involving the $s on the definition of n and in the echo command in double quotes, as such:

#!/bin/bash +x
    echo -n "String: "
    read s
    n=`expr index "$s" " "`
    if [ $n -gt 0 ]; then
            m=`expr $n - 1`
            echo "Nome: " `expr substr "$s" 1 $m`
    fi

This bottom one works just fine. But why? What difference does the " " make?


Solution

  • Without the double quotes, your expr command is:

    expr index John Smith " "
    

    That reports a syntax error, because the index operator should be followed by only two arguments, but you gave it three arguments. Since it gets an error, it doesn't output a result, so $n is set to an empty string. Then the if command becomes

    if [ -gt 0 ]
    

    which is missing one of the operands.

    Motto: always quote variables unless you need the value to undergo word splitting or globbing.