proper way to detect shell exit code when errexit option set

后端 未结 14 1849
甜味超标
甜味超标 2021-01-30 12:52

I prefer to write solid shell code, so the errexit & nounset is alway set.

The following code will stop at bad_command line

#!/bin/b         


        
14条回答
  •  我在风中等你
    2021-01-30 13:39

    I cobbled together a (hopefully) textbook example from all the answers:

    #!/usr/bin/env bash
    
    # exit immediately on error
    set -o errexit
    
    file='dfkjlfdlkj'
    # Turn off 'exit immediately on error' during the command substitution
    blah=$(set +o errexit && ls $file) && rc=$? || rc=$?
    echo $blah
    # Do something special if $rc
    (( $rc )) && echo failure && exit 1
    echo success
    

提交回复
热议问题