proper way to detect shell exit code when errexit option set

后端 未结 14 1511
甜味超标
甜味超标 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条回答
  •  -上瘾入骨i
    2021-01-30 13:37

    A slight variation of the answer given by @rrauenza. Since the && rc=$? part is their answer will always be equal to && rc=0 one can as well set rc to 0 before running the command. The result ends up more readable in my opinion because the variable is defined upfront in its own line of code and is only changed if the command exits with a non-zero exit status. If nounset is also given, then it's now clear that rc was indeed never undefined. This also avoids mixing && and || in the same line which might be confusing because one might not always know the operator precedence by heart.

    #!/bin/sh                                                                       
    set -eu
    
    rc=0
    cat /tmp/doesnotexist || rc=$?                                         
    echo exitcode: $rc        
    
    rc=0
    cat /dev/null || rc=$?                                                 
    echo exitcode: $rc   
    

    Output:

    cat: /tmp/doesnotexist: No such file or directory
    exitcode: 1
    exitcode: 0
    

提交回复
热议问题