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

后端 未结 10 1794
北荒
北荒 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 will need to call your function in a sub shell (inside brackets ()) to achieve this.

    I think you want to write your script like this:

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

    Then the output is (as desired):

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

提交回复
热议问题