命令里面的if语句的bash脚本

mya*_*hya 21 bash conditional if-statement syntax-error

我有以下行作为更大的bash脚本的一部分:

if [ `packages/TinySVM-0.09/bin/svm_learn 2>&1| grep TinySVM | wc -l | cut -c0-7 | sed 's/^  *//g'` -eq 1 ] 
Run Code Online (Sandbox Code Playgroud)

在运行脚本时,我得到:

./install.sh:219行:[: - eq:一元运算符预期

其中219行是上面的行.有什么修复建议吗?

Sie*_*geX 31

当您使用test内置via时[,会发生这种情况,并且左侧表达式返回NUL.您可以通过以下方式解决此问题:

if [ x`some | expression | here` = x1 ]; then
Run Code Online (Sandbox Code Playgroud)

或者,既然你已经在使用bash,你可以使用它(( ))没有这个问题的更好的语法,并且:

if (( $(some | expression | here) == 1 )); then
Run Code Online (Sandbox Code Playgroud)

请注意,我还使用$()了反引号命令替换``因为后者是非POSIX并且已弃用


Ale*_*ing 27

您无需任何其他语法即可运行命令.例如,以下检查grep的退出代码以确定正则表达式是否匹配:

if ! grep -q "$word" /usr/share/dict/words
then
    echo "Word $word is not valid word!"
fi
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 8

发生此错误是因为您的命令替换没有返回任何有效使您的测试看起来像:

if [ -eq 1 ] 
Run Code Online (Sandbox Code Playgroud)

解决这个问题的常用方法是在等式的两边附加一些常量,这样任何操作数都不会变为空:

if [ x`packages/TinySVM-0.09/bin/svm_learn 2>&1| grep TinySVM | wc -l | cut -c0-7 | sed 's/^  *//g'` = x1 ] 
Run Code Online (Sandbox Code Playgroud)

注意=正在使用,因为我们现在正在比较字符串.


Pau*_*ce. 6

您可以在比较的两侧添加"x",或者您可以引用左侧:

[ "$(command | pipeline)" = 1 ]
Run Code Online (Sandbox Code Playgroud)

我不明白的cut,并sed在年底是.wc -l管道中的输出只是一个数字.


SOU*_*ser 5

尝试[[test_expression]]; 代替[test_expression];