I am trying to figure out the syntax for having a while loop and an if statement that checks for more than one condition, in a single-line shell script.
Executing something like this...
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ] echo $i " not equal to 3 or 5"; else echo $i; i=`expr $i + 1`; done
...I get the error
bash: syntax error near unexpected token `else'
On another hand if I remove the semicolon from between ...3 or 5" and else echo..., and try something like this...
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ] echo $i " not equal to 3 or 5" else echo $i; i=`expr $i + 1`; done
...then I get the error:
syntax error near unexpected token `done'
This is on an Ubuntu 14.04, in case it matters.
Am I perhaps missing some kind of a parenthesis somewhere, or is it something else?
This should work:
i=2; while [ $i -le 10 ]; do if [ $i -ne 3 -a $i -ne 5 ]; then echo $i " not equal to 3 or 5"; else echo $i; fi; i=`expr $i + 1`; done
and this should also work:
i=2; while [ $i -le 10 ]; do [ $i -ne 3 -a $i -ne 5 ] && echo "$i not equal to 3 or 5" || echo $i; i=$((i+1)); done
But I am not sure if it makes sense to write this in only one line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With