Bash conditional | getting logic wrong?

I have a file

cat <<EOF > /tmp/test
Line one
Line two 
Line three
EOF

Now I am trying to get the exit stat ($?) of 1 if any text is found and 0 if any text is not found using grep, i.e. just reversing the exit status of grep

# (snippet 1) this one is not working!!! retval $? should be 1
grep -q 'one' /tmp/test && false || true
echo $?


# (snippet 2) but this one is working - retval is 1
grep -q 'one' /tmp/test
if [ $? -eq 0 ]; then 
    false
else 
    true
fi
echo $?

What am I missing in snippet 1?

cmd || true will always return 0, since either cmd succeeds or true does. In your snippet #1, cmd is grep && false . That is always false, since either grep fails or false does.

Your snippet #1 therefore reduces to false || true . That will always return 0.

Since your grep command succeeds:

(grep && false) || true
(true && false) || true
(false) || true
true

Regards,
Alister

1 Like

Is there a way to shorten snippet 2?

Looks like you just want to invert the status:

! grep -q 'one' /tmp/test

Regards,
Alister

1 Like

Cool. Thanks.