tags:

views:

42

answers:

3

I want to represent multiple condition like this:

if [ ( $g -eq 1 -a "$c" = "123" ) -o ( $g -eq 2 -a "$c" = "456" ) ]   
then  
    echo abc;  
else  
    echo efg;   
fi  

but when I execute the script, it shows

syntax error at line 15: `[' unexpected, 

where line 15 is the one showing if ....

What is wrong with this condition? I guess something wrong with ().

A: 

Classic technique (escape metacharacters):

if [ \( $g -eq 1 -a "$c" = "123" \) -o \( $g -eq 2 -a "$c" = "456" \) ]
then echo abc
else echo efg
fi

I tried various tricks with '[[ ... ]]' without success - even escaping the parentheses did not seem to work.


Isn't it a classic question?

I would have thought so. However, there is an alternative, namely:

if [ $g -eq 1 -a "$c" = "123" ] || [ $g -eq 2 -a "$c" = "456" ]
then echo abc
else echo efg
fi

Indeed, if you read the 'portable shell' guidelines for the autoconf tool or related packages, this notation - using '||' and '&&' - is what they recommend. I suppose you could even go so far as:

if [ $g -eq 1 ] && [ "$c" = "123" ]
then echo abc
elif [ $g -eq 2 ] && [ "$c" = "456" ]
then echo abc
else echo efg
fi

Where the actions are as trivial as echoing, this isn't bad. When the action block to be repeated is multiple lines, the repetition is too painful and one of the earlier versions is preferable.

Jonathan Leffler
Thanks a lot, \( works. why didn't I find the answer from other any website? isn't it an classic question?
+3  A: 

In Bash:

if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]
Dennis Williamson
A: 
$ g=3
$ c=133
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
efg
$ g=1
$ c=123
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
abc
ghostdog74