How to disable set -e for an individual command?

  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=$?

Tags:

Bash