Command inside if statement of bash script [duplicate] Command inside if statement of bash script [duplicate] bash bash

Command inside if statement of bash script [duplicate]


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/wordsthen    echo "Word $word is not valid word!"fi


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


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.