Hi,
I trying to test two condition together (AND) under bash but it’s not working…
The goal is ti have True when two variables are either not set or empty (empty string)
I’ve tried
if [[ -n VARIABLE1 && -n VARIABLE2 ]]; then
echo "OK"
fi
Here I get the “OK” no matter what .
Thanks.
Thank you all for yours input
What finally did work
if [[ -z VARIABLE1 && -z VARIABLE2 ]]; then echo "OK" fi
If only Linux was using Python syntax that would be so much more intuitive…
[ condition1 ] && [ condition2 ] && echo "Good" || echo "Bad"
Explanation
[
is an alias for the programtest
, so you can callman test
for more info.
&&
is bash syntax for conjunction. In A && B, B will only be called if A returned a exit code >0 (error). You can callman bash
for more info.
||
is bash syntax for disjunction. In A || B, B will only be called if A returned exit code =0 (success).true
andfalse
are programs that just return exit codes 0 respectively 1.
If you want true for empty strings, you want -z not -n
if [[ -z "VARIABLE1" && -z "VARIABLE2" ]]; then echo "OK" fi
To check for an empty string, use
-z
.-n
checks to see if a string is not empty.You need to reference the value of the variable, ie:
if [[ -n "$VARIABLE1" && -n "$VARIABLE2" ]]; then echo "OK" fi
not working, both variables do not exist and the
echo "OK"
do not trigger.
Try this:
#!/usr/bin/env bash a="" if [[ -z "${a}" && -z "${b}" ]]; then echo "OK" else echo "Not OK" fi a="OK" if [[ -n "${a}" && -z "${b}" ]]; then echo "More ${a}" else echo "More Unokay" fi
Could try:
if [ condition1 ] && [ condition2 ]; then echo "OK" fi