LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash if statement (https://www.linuxquestions.org/questions/programming-9/bash-if-statement-621448/)

jstu 02-15-2008 03:57 PM

bash if statement
 
Very simple question, but it is stumping me. Could anyone explain why this if statement prints the value of $a?

Code:

a="hey"
if [[ $a != "hey" || $a != "what" ]]; then
        echo $a
fi


Thanks

pixellany 02-15-2008 04:15 PM

The if statement contains the boolean "OR" operator (||). Thus if either expression is true, then the if is true, and it goes to the echo command.

$a != "what" is true.....therefore the if is true.

jstu 02-15-2008 04:18 PM

Thanks. I just didnt understand the logic behind the or. I figured that sicne the first one was false it should have stopped.

dive 02-15-2008 04:42 PM

|| = or
&& = and

urka58 02-15-2008 04:43 PM

Logical operations (and/or) are somehow confusing..
You should preferably refer to them in terms of exit status of the command not in terms of the common meaning of yes/no. In this case test exits 0 (true) , so the script continues to the further line (echo bal_bla).
Ciao

jstu 02-15-2008 05:35 PM

Thanks. I guess I just didnt know when the if statement exited.

JWPurple 02-15-2008 07:34 PM

Further, "short-cut" evaluation is used (as in C):

In an "or" condition, if the first term is true, there's no reason to evaluate the rest, and it's skipped.

In an "and" condition, if the first term is false, there's no reason to evaluate the rest, and it's skipped.

ghostdog74 02-15-2008 07:48 PM

Quote:

Originally Posted by jstu (Post 3058519)
Very simple question, but it is stumping me. Could anyone explain why this if statement prints the value of $a?

Code:

a="hey"
if [[ $a != "hey" || $a != "what" ]]; then
        echo $a
fi


Thanks

Code:

a="hey"
case $a in
  hey|what ) echo "no";;
  * ) echo "yes";;
esac



All times are GMT -5. The time now is 05:37 AM.