Search code examples
shellif-statementconditional-statementsksh

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.

Solution

  • 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.