How do I get the effect and usefulness of “set -e” inside a shell function?

后端 未结 10 1835
北荒
北荒 2020-11-28 06:18

set -e (or a script starting with #!/bin/sh -e) is extremely useful to automatically bomb out if there is a problem. It saves me having to error ch

10条回答
  •  庸人自扰
    2020-11-28 06:51

    You may directly use a subshell as your function definition and set it to exit immediately with set -e. This would limit the scope of set -e to the function subshell only and would later avoid switching between set +e and set -e.

    In addition, you can use a variable assignment in the if test and then echo the result in an additional else statement.

    # use subshell for function definition
    f() (
       set -exo pipefail
       echo a
       false
       echo Should NOT get HERE
       exit 0
    )
    
    # next line also works for non-subshell function given by agsamek above
    #if ret="$( set -e && f )" ; then 
    if ret="$( f )" ; then
       true
    else
       echo "$ret"
    fi
    
    # prints
    # ++ echo a
    # ++ false
    # a
    

提交回复
热议问题