KornShell - grouping conditions in an IF statement
54,037
Solution 1
Are you looking for this?
#!/bin/ksh
if [[ -n $1 || -n $2 ]] && [[ $1 == "$2" || $1 == x ]]; then
echo "True"
else
echo "False"
fi
Run:
$ ./if.sh "" ""
False
$ ./if.sh 1 2
False
$ ./if.sh 1 1
True
$ ./if.sh x 2
True
If you are wondering why your code fails:
- You need to escape the parentheses
\(
- There have to be a spaces around the parantheses
- And you have a typo, there is a superfluous
"
floating around
So this ...
if [ ( "$var1" != "" -o "$var2" != "") -a ( "$var1" = "$var2" -o " "$var1" = "x") ]; then
typo ---^ ^
^------------------ missing spaces --------^
... should look like this ...
if [ \( "$var1" != "" -o "$var2" != "" \) -a \( "$var1" = "$var2" -o "$var1" = "x" \) ]; then
and then it will work.
Solution 2
You need to use double square brackets.. [[--------]]
Hope it helps.
Regards.
Comments
-
HSM about 4 years
I got the following snippet failing on KornShell (ksh):
var1="1" var2="2" if [ ( "$var1" != "" -o "$var2" != "") -a ( "$var1" = "$var2" -o " "$var1" = "x") ]; then echo "True" else echo "False" fi
ksh: syntax error: `"$var1"' unexpected
As I understand, this fails because the parentheses run in a subshell where var1 is not recognized. So how could sets of conditions be grouped inside the square brackets?
N.B. I already know the following solutions and do not want to use them:
- Put the conditions in separate nested if statements.
- Optimize/rearrange conditions in order to put them in only one set.
-
HSM almost 11 yearsThanks a lot for your answer Adrian, it's much appreciated. Escaping the parentheses did not work I still got "ksh: [: missing ]" as error. I used the first proposition: breaking down the square brackets into two ANDed sets.