Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.
When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
Use -a
(for and) and -o
(for or) operations.
tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Update
Actually you could still use &&
and ||
with the -eq
operation. So your script would be like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
echo "$my_error_flag"
else
echo "no flag"
fi
Although in your case you can discard the last two expressions and just stick with one or operation like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ]; then
echo "$my_error_flag"
else
echo "no flag"
fi
You can use either [[
or ((
keyword. When you use [[
keyword, you have to use string operators such as -eq
, -lt
. I think, ((
is most preferred for arithmetic, because you can directly use operators such as ==
, <
and >
.
Using [[
operator
a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
echo "Error"
else
echo "No Error"
fi
Using ((
operator
a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
echo "Error"
else
echo "No Error"
fi
Do not use -a
or -o
operators Since it is not Portable.
Please try following
if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
echo "WORKING"
else
echo "Out of range!"
You can get some inspiration by reading an entrypoint.sh
script written by the contributors from MySQL that checks whether the specified variables were set.
As the script shows, you can pipe them with -a
, e.g.:
if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
...
fi
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