Will
Will

Reputation: 2410

SHELL - AND operation within IF statement

Assuming thoses functions :

return_0() {
   return 0
}

return_1() {
   return 1
}

Then the following code :

if return_0; then
   echo "we're in" # this will be displayed
fi

if return_1; then
   echo "we aren't" # this won't be displayed
fi

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

Why I am getting into the last ifstatement ? Aren't we supposed to be out of the condition with those 0 and 1 ?

Upvotes: 2

Views: 120

Answers (2)

kvantour
kvantour

Reputation: 26491

When you execute

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

You execute the line return_0 -a return_1. This actually means that you pass -a and return_1 as arguments to return_0. If you want to have an and operation, you should make use of the && syntax.

if return_0 && return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

The useful information to understand this is:

AND and OR lists are sequences of one of more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

Upvotes: 4

kojiro
kojiro

Reputation: 77137

-a is one of the options of the test command (which is also implemented by [ and [[). So you can't just use -a by itself. You probably want to use &&, which is a control operator token for an AND list.

if return_0 && return_1; then ...

You can use -a to tell test to "and" two different test expressions, like

if test -r /file -a -x /file; then
    echo 'file is readable and executable'
fi

But this is equivalent to

if [ -r /file -a -x /file ]; then ...

which may be more readable because the brackets make the test part of the expression clearer.

See the Bash Reference Manual for further information on...

Upvotes: 4

Related Questions