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

后端 未结 10 1833
北荒
北荒 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:35

    If a subshell isn't an option (say you need to do something crazy like set a variable) then you can just check every single command that might fail and deal with it by appending || return $?. This causes the function to return the error code on failure.

    It's ugly, but it works

    #!/bin/sh
    set -e
    
    my_function() {
        echo "the following command could fail:"
        false || return $?
        echo "this is after the command that fails"
    }
    
    if ! my_function; then
        echo "dealing with the problem"
    fi
    
    echo "run this all the time regardless of the success of my_function"
    

    gives

    the following command could fail:
    dealing with the problem
    run this all the time regardless of the success of my_function
    

提交回复
热议问题