HSM
HSM

Reputation: 101

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:

Upvotes: 4

Views: 58168

Answers (2)

Sugan P
Sugan P

Reputation: 11

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

Hope it helps.

Regards.

Upvotes: 1

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45626

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.

Upvotes: 6

Related Questions