2

In C language we can use if(a==b&&a==c) we can make a double and statement is that possible in unix, to be specific in a shell script?

1 Answer 1

6
if [ a == b ] && [ a == c ]; then
    // passed conditions
fi

Nesting them with bash specific syntax is not so bad:

if [[ ( a == b && a == c) || b == c ]]; then

But I believe it gets extremely ugly if you want to be sh compatible.

9
  • 3
    if [ "$a" = "$b" -a "$a" = "$c" ]; then // passed; fi is standard and saves a test
    – doneal24
    Commented Dec 11, 2013 at 18:58
  • @DougO'Neal If the variables can contain arbitary data then this is not safe in general. (I can't find a flaw with this specific expression though.) The shell has no way to know which arguments are operators and which arguments are operands: some expressions are ambiguous. For example try to parse [ -n != -o -n = -o ]. Ksh93 says yes (I presume because it sees [ ( -n '!=' ) -o ( '-n' = '-o' ) ]]), but pdksh, bash, dash and zsh choke. Commented Dec 12, 2013 at 0:12
  • @Gilles The double quotes around the variables makes them safe. a='-n'; b='!='; c=''; if [ "$a" = "$b" -a "$a" = "$c" ]; then echo passed; else echo failed; fi parses just fine.
    – doneal24
    Commented Dec 12, 2013 at 17:57
  • @DougO'Neal No, the quotes change nothing inside [ … ]. This is an ordinary command subject to the ordinary parsing rule, it is not special syntax like [[ … ]]. Commented Dec 12, 2013 at 19:08
  • @Gilles Then can you show me how you set up the example above using quoted variables so that it doesn't parse in bash?
    – doneal24
    Commented Dec 12, 2013 at 20:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .