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?
$s
gets split in two different words,John
andSmith
, 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 is0
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. – Enlico Oct 19 '20 at 14:05