为什么在这个脚本中
#!/bin/sh
if [ $1='all' ];
then
echo $1
echo "all"
fi
无论如何都打印了???
例如,我这样做:./thescript.sh
并且我清楚发现$1是空的。但仍然全部打印出来。为什么?当全部通过时如何打印“全部”
最佳答案
shellcheck有解决办法:
SC2077: You need spaces around the comparison operator.
更改为
if [ $1 = 'all' ];
如果没有空格,[
和 ]
之间的内容将被视为一个表达式,man [
表示
"STRING equivalent to -n STRING
因此任何非空字符串都被视为true
。 (即 if [ ""];
将为 false
。)
也就是说,您最好在 shebang 中指定您想要的 shell。在某些系统上,/bin/sh
可能是 bash
,在其他系统上,/bin/dash
或其他内容。选择您的 shell,避免因错误假设您实际获得的 shell 而出现任何问题。
关于shell脚本,如果无论如何都会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70254232/