In a Bash script, how can I exit the entire script if a certain condition occurs?

后端 未结 7 1717
我在风中等你
我在风中等你 2020-11-29 14:30

I\'m writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I\'ll just abort the

7条回答
  •  渐次进展
    2020-11-29 14:59

    Use set -e

    #!/bin/bash
    
    set -e
    
    /bin/command-that-fails
    /bin/command-that-fails2
    

    The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run.

    If you were to check the return status of every single command, your script would look like this:

    #!/bin/bash
    
    # I'm assuming you're using make
    
    cd /project-dir
    make
    if [[ $? -ne 0 ]] ; then
        exit 1
    fi
    
    cd /project-dir2
    make
    if [[ $? -ne 0 ]] ; then
        exit 1
    fi
    

    With set -e it would look like:

    #!/bin/bash
    
    set -e
    
    cd /project-dir
    make
    
    cd /project-dir2
    make
    

    Any command that fails will cause the entire script to fail and return an exit status you can check with $?. If your script is very long or you're building a lot of stuff it's going to get pretty ugly if you add return status checks everywhere.

提交回复
热议问题