如果脚本有
if [ $1 == "-?" ]; then #line 4
echo "usage: ...."
fi
Run Code Online (Sandbox Code Playgroud)
当脚本在没有任何参数的情况下运行时,它会抱怨
./script.sh: line 4: [: ==: unary operator expected
Run Code Online (Sandbox Code Playgroud)
但如果相反
if [ "$1" == "-?" ]; then #line 4
echo "usage: ...."
fi
Run Code Online (Sandbox Code Playgroud)
一切都很好
这是为什么?
谢谢
如果第一个参数缺失或为空,则第一个脚本的计算结果为:
if [ == "-?" ] ; then
Run Code Online (Sandbox Code Playgroud)
...这是一个语法错误.正如您所注意到的,为了防止您需要使用"",它会评估为:
if [ "" == "-?" ] ; then
Run Code Online (Sandbox Code Playgroud)
AFAIK这是由于原始Bourne shell的工作方式.你应该养成将变量括起来的习惯,""以便在包含空格的参数中正常工作.例如,如果你像这样调用你的脚本:
./myScript "first argument has spaces"
Run Code Online (Sandbox Code Playgroud)
然后你的第一个脚本将评估为:
if [ first argument has spaces == "-?" ] ; then
Run Code Online (Sandbox Code Playgroud)
这也是一个语法错误.rm $1如果您传递带空格的文件名,那么事情就会无法完成.做rm "$1"代替.