When the errexit option is enabled any failing command will cause the script to exit. I want to invert this behavior for certain commands that are expected to fail. That is: I want to continue only if the indicated command fails.

I currently do something like this, it's ugly:

some_test() { 
    # retuns nonzero if some condition is met, and zero otherwise

some_change() {
    # makes a change that should alter the return code of the above test

set -e

echo "expected success, found it"


set +e
some_test           # expect failure

if [[ $? -eq 0 ]]
   echo "expected failure, found success"
   echo "expected failure, found it"

set -e

# ...more testing below

I am looking for something more concise. I know that I can tolerate a failing command like this:

some_test && true

But I don't want to merely tolerate failure, I want to assert failure. If the second test passes, I want my script to fail.

if my_command; then false; else true; fi

I don't believe it's possible to emulate this using conditional gymnastics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.