How to disable set -e for an individual command?

The set -e command makes a bash script fail immediately when any command returns an non-zero exit code.

  1. Is there an easy and elegant way to disable this behaviour for an individual command within a script?

  2. At which places is this functionality documented in the Bash Reference Manual (http://www.gnu.org/software/bash/manual/bashref.html)?


  1. Something like this:

    #!/usr/bin/env bash
    
    set -e
    echo hi
    
    # disable exitting on error temporarily
    set +e
    aoeuidhtn
    echo next line
    
    # bring it back
    set -e
    ao
    
    echo next line
    

    Run:

    $ ./test.sh
    hi
    ./test.sh: line 7: aoeuidhtn: command not found
    next line
    ./test.sh: line 11: ao: command not found
    
  2. It's described in set builtin help:

    $ type set
    set is a shell builtin
    $ help set
    (...)
    Using + rather than - causes these flags to be turned off.
    

The same is documented here: https://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin.


An alternative to unsetting the bail on error would be to force a success no matter what. You can do something like this:

cmd_to_run || true

That will return 0 (true), so the set -e shouldn't be triggered


If you are trying to catch the return/error code (function or fork), this works:

function xyz {
    return 2
}

xyz && RC=$? || RC=$?

If the the "exit immediately shell option" applies or is ignored depends on the context of the executed command (see Bash Reference Manual section on the Set Builtin - thanks to Arkadiusz Drabczyk).

Especially, the option is ignored if a command is part of the test in an if statement. Therefore it is possible to execute a command and check for its success or failure within an "exit immediately context" using an if statement like this:

#!/bin/bash

set -e

# Uncomment next line to see set -e effect:
#blubb

if blubb; then
  echo "Command blubb was succesful."
else 
  echo "Command blubb failed. Exit code: $?"
fi
echo "Script exited normally."

It is possible to omit the "then" statement and use fewer lines:

if blubb; then :;
else echo "Command blubb failed. Exit code: $?"; fi