【发布时间】:2020-11-11 03:05:04
【问题描述】:
这让我很难过。刚接触 shell 脚本并在 macOS Catalina 中使用 ZSH(尽管我认为在 bash 中也会发生同样的事情。)
我正在使用以下脚本,并将其保存在一个名为 f 的文件中,该文件没有扩展名。我用-x chmod'd 将它放在我的路径变量中的本地bin 文件夹中。
clear
echo "Argument Count: $#"
if [ $# == 0 ]; # Run if no arguments
then
echo "You ran this with no arguments!"
exit 0
fi
if [ $1 == "a" ]; # Run if the first argument is 'a'
then
echo "You ran A!"
exit 0
fi
# Run if nothing matches the above
echo "No matches!"
以上工作如我所料。如果我输入这个...
f
我明白了……
Argument Count: 0
You ran this with no arguments!
如果我输入这个...
f a
我明白了……
Argument Count: 1
You ran A!
最后,如果我输入这个...
f b (or f c, f foo, etc.)
我明白了……
Argument Count: 1
No matches.
再次,完全按照我的预期工作。
但是,如果我将脚本更改为这样,我只需注释掉第一个 if 块...
clear
echo "Argument Count: $#"
# if [ $# == 0 ]; # Run if no arguments
# then
# echo "You ran this with no arguments!"
# exit 0
# fi
if [ $1 == "a" ]; # Run if the first argument is 'a'
then
echo "You ran A!"
exit 0
fi
# Run if nothing matches the above
echo "No matches!"
...我自己输入f,我现在明白了!
Argument Count: 0
/Users/[redacted]/bin/f: line 11: [: ==: unary operator expected
No matches!
注意:第 11 行是带有注释的行 # Run if the first argument is 'a'
更奇怪的是,如果我输入以下内容,它会直接运行它所抱怨的第 11 行的代码...
f a
我明白了,它工作正常!
Argument Count: 1
You ran A!
那么我到底错过了什么??
【问题讨论】:
标签: bash shell zsh macos-catalina