bash bash脚本的if语句中的命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5276393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:16:42  来源:igfitidea点击:

Command inside if statement of bash script

bashif-statementconditionalsyntax-error

提问by myahya

I have the following line as part of a much bigger bash script:

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

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

upon running the script, I get:

运行脚本后,我得到:

./install.sh: line 219: [: -eq: unary operator expected

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

Where line 219 is the line above. Any suggestions for a fix?

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

回答by SiegeX

This happens when you are using the testbuiltin via [and your left side expression returns NUL. You can fix this by the use of:

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

if [ x`some | expression | here` = x1 ]; then

Or, since you're already using bash you can use its much nicer (( ))syntax which doesn't have this problem and do:

或者,由于您已经在使用 bash,您可以使用它的更好的(( ))语法,它没有这个问题,并执行以下操作:

if (( $(some | expression | here) == 1 )); then

Note that I also used $()for command substitution over backticks `` as the latter is non-POSIX and deprecated

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

回答by Alex Spurling

You can run your command without any additional syntax. For example, the following checks the exit code of grep to determine whether the regular expression matches or not:

您可以在没有任何附加语法的情况下运行您的命令。例如,以下检查 grep 的退出代码以确定正则表达式是否匹配:

if ! grep -q "$word" /usr/share/dict/words
then
    echo "Word $word is not valid word!"
fi

回答by codaddict

The error occurs because your command substitution returns nothing effectively making your test look like:

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

if [ -eq 1 ] 

A common way to fix this is to append some constant on both sides of the equation, so that no operand becomes empty at any time:

解决此问题的常见方法是在等式两边附加一些常量,以便任何时候都没有操作数变为空:

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

Note that =is being used as we are now comparing strings.

请注意,=我们现在正在比较字符串时正在使用它。

回答by SOUser

Try [[ test_expression ]]; instead of [ test_expression ];

试试 [[ test_expression ]]; 而不是 [ test_expression ];

回答by Paused until further notice.

You could add an "x" to both sides of the comparison or you could just quote the left side:

您可以在比较的两侧添加一个“x”,或者您可以只引用左侧:

[ "$(command | pipeline)" = 1 ]

I don't understand what the cutand sedat the end are for. The output of wc -lin a pipeline is simply a number.

我不明白的cutsed是在年底。wc -l管道中的输出只是一个数字。