0

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?

Daniel Oscar
  • 287
  • 1
  • 9
  • 1
    The problem is that `$s` gets split in two different words, `John` and `Smith`, so you are providing `-gt` with two arguments on the left, whereas it expetcs only one (and yeah, another one on the right too, which is `0` in your case). Using double quotes prevents the splitting, while letting the variable expansion take place (unlike single quotes). Therefore, beside the question that this was marked duplicate of, I would also point to [Difference between single and double quotes in Bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash). – Enlico Oct 19 '20 at 14:05

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612