Determine if `set -e` flag if is active in bash

前端 未结 4 977
生来不讨喜
生来不讨喜 2021-01-14 03:44

In a bash script/shell, is there a programmatic way to determine if the set -e flag is active?

I just need a boolean letting me know if it\'s on/off.

相关标签:
4条回答
  • 2021-01-14 04:24

    You can check the $- variable to see whether the e option is enabled:

    [[ $- =~ e ]]
    

    From help set:

    The current set of flags may be found in $-.
    
    0 讨论(0)
  • 2021-01-14 04:27

    From help test:

        -o OPTION      True if the shell option OPTION is enabled.
    

    Thus:

    [ -o errexit ]
    
    0 讨论(0)
  • 2021-01-14 04:38

    You can also use the exit code of shopt:

    if shopt -qo errexit; then 
        echo enabled
        # do something
    fi
    
    0 讨论(0)
  • 2021-01-14 04:41
    $ set -e
    $ if grep -q 'errexit' <<<"$SHELLOPTS";then echo "set -e is enabled";else echo "set -e is disabled";fi
    set -e is enabled
    $ set +e
    $ if grep -q 'errexit' <<<"$SHELLOPTS";then echo "set -e is enabled";else echo "set -e is disabled";fi
    set -e is disabled
    
    0 讨论(0)
提交回复
热议问题