Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KornShell - grouping conditions in an IF statement

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.
like image 641
HSM Avatar asked Oct 18 '25 02:10

HSM


2 Answers

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:

  1. You need to escape the parentheses \(
  2. There have to be a spaces around the parantheses
  3. 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.

like image 54
Adrian Frühwirth Avatar answered Oct 20 '25 16:10

Adrian Frühwirth


You need to use double square brackets.. [[--------]]

Hope it helps.

Regards.

like image 36
Sugan P Avatar answered Oct 20 '25 18:10

Sugan P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!