1

We know that it is possible to do if command ; then something ; fi, where the status returned from command is interpreted as boolean (0==true). We also know that is ok doing if [[ $a > $b || $c == yes ]] ; then something; fi.

But I'm curious because we are not allowed to combine commands like Boolean expressions using "if", as in if cmd1 || cmd2; then ; something; fi. Or can we?

There is other ways of doing this without "if" or even with nested if. However, I'm interested on using if :-).

Appreciate any comment.

2 Answers 2

3

That is correct. The condition to an if statement is defined to be a list, which very roughly speaking is either a single pipeline, or two lists joined by && or ||. These are not Boolean operators, although there is a resemblance. a && b runs a, then runs b if a succeeds. a || b runs a, then runs b if a fails.

Compare

if [[ $a > $b || $c == yes ]]; then   # conditional operators
if [[ $a > $b ]] || [[ $c == yes ]]; then   # shell operators

Given that [[ ... ]] is a built-in command, there is very little difference between the two. However, the shell operators have equal precedence, while the conditional operator && has higher precedence than conditional ||. That is

if a || b && c; then # same as (a || b) && c
if [[ a || b && c ]]; then # same as a || (b && c)
Sign up to request clarification or add additional context in comments.

Comments

0

I`ll just leave this here.

check_and() {
    if grep -q A <<<"$1" && grep -q C <<<"$1"; then
        echo YES
    else
        echo NO
    fi
}

check_or() {
    if grep -q A <<<"$1" || grep -q C <<<"$1"; then
        echo YES
    else
        echo NO
    fi
}

check_and ABC # YES
check_and ABD # NO
check_and ZBC # NO
check_and ZBD # NO

check_or ABC # YES
check_or ABD # YES
check_or ZBC # YES
check_or ZBD # NO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.