为什么在 shell 脚本中定义此变量需要双引号?

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

考虑这段代码:

#!/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

当我用 运行 并在提示符中写入“John Smith”时,我收到此错误:

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

我可以通过在 n 的定义中包含 $s 和双引号中的 echo 命令来修复它,这样:

#!/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

下面这个效果很好。但为什么? “ ”有什么区别?

没有双引号,您的 expr 命令是:

expr index John Smith " "

报告语法错误,因为 index 运算符后面应该只有两个参数,但你给了它三个参数。由于出现错误,因此不会输出结果,因此 $n 设置为空字符串。然后 if 命令变成

if [ -gt 0 ]

其中缺少一个操作数。

格言:除非您需要对值进行分词或通配,否则始终引用变量。