Bash scripting, multiple conditions in while loop Bash scripting, multiple conditions in while loop bash bash

Bash scripting, multiple conditions in while loop


The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).# Quotes strongly recommended to guard against empty or undefined variables.while [ "$stats" -gt 300 -o "$stats" -eq 0 ]# Two POSIX test commands joined in a list with ||.# Quotes strongly recommended to guard against empty or undefined variables.while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]# Two bash conditional expressions joined in a list with ||.while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]# A single bash conditional expression with the || operator.while [[ $stats -gt 300 || $stats -eq 0 ]]# Two bash arithmetic expressions joined in a list with ||.# $ optional, as a string can only be interpreted as a variablewhile (( stats > 300 )) || (( stats == 0 ))# And finally, a single bash arithmetic expression with the || operator.# $ optional, as a string can only be interpreted as a variablewhile (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.


Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.


The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.

Alternatively:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]