Shell scripting: die on any error

后端 未结 3 1753
天命终不由人
天命终不由人 2020-12-23 20:32

Suppose a shell script (/bin/sh or /bin/bash) contained several commands. How can I cleanly make the script terminate if any of the commands has a failing exit status? Obv

相关标签:
3条回答
  • 2020-12-23 20:45

    With standard sh and bash, you can

    set -e
    

    It will

    $ help set
    ...
            -e  Exit immediately if a command exits with a non-zero status.
    

    It also works (from what I could gather) with zsh. It also should work for any Bourne shell descendant.

    With csh/tcsh, you have to launch your script with #!/bin/csh -e

    0 讨论(0)
  • 2020-12-23 20:52

    May be you could use:

    $ <any_command> || exit 1
    
    0 讨论(0)
  • 2020-12-23 20:59

    You can check $? to see what the most recent exit code is..

    e.g

    #!/bin/sh
    # A Tidier approach
    
    check_errs()
    {
      # Function. Parameter 1 is the return code
      # Para. 2 is text to display on failure.
      if [ "${1}" -ne "0" ]; then
        echo "ERROR # ${1} : ${2}"
        # as a bonus, make our script exit with the right error code.
        exit ${1}
      fi
    }
    
    ### main script starts here ###
    
    grep "^${1}:" /etc/passwd > /dev/null 2>&1
    check_errs $? "User ${1} not found in /etc/passwd"
    USERNAME=`grep "^${1}:" /etc/passwd|cut -d":" -f1`
    check_errs $? "Cut returned an error"
    echo "USERNAME: $USERNAME"
    check_errs $? "echo returned an error - very strange!"
    
    0 讨论(0)
提交回复
热议问题