Command inside if statement of bash script [duplicate]

守給你的承諾、 提交于 2019-12-20 09:49:42

问题


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

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

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


回答1:


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

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:

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

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




回答2:


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:

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



回答3:


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.




回答4:


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

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

I don't understand what the cut and sed at the end are for. The output of wc -l in a pipeline is simply a number.




回答5:


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



来源:https://stackoverflow.com/questions/5276393/command-inside-if-statement-of-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!