if(grep "9" ls ); then echo "hello"; else echo "hi"; fi
when I execute the above command output is the below one
grep: ls: No such file or directory
hi
how can I just get hi(only condition) as output
if(grep "9" ls ); then echo "hello"; else echo "hi"; fi
when I execute the above command output is the below one
grep: ls: No such file or directory
hi
how can I just get hi(only condition) as output
grep -q "9" ls 2>/dev/null || echo "hi"
-q
will not print grep output itself
2>/dev/null
is not necessary, but suppresses possible error messages making the output 'more clean' (e.g. no grep: ls: No such file or directory
)
Or even better solution on the recommendation of @Aaron:
grep -qs "9" ls || echo "hi"
TL; DR
if( grep -q "9" ls 2>/dev/null); then echo "hello"; else echo "hi"; fi
OR
if( grep -sq 9 ls); then echo "hello"; else echo "hi"; fi
Explanation
You can use man grep
command in terminal to see how -q
suppresses the output. Refer this link to see why 2>/dev/null
is used so that STDERR is not shown.
As OP's question shows 2 conditions. If and else, I suggested this solution. But, if you just want to have else
part, you can refer to Alex's answer