proper way to detect shell exit code when errexit option set

后端 未结 14 1852
甜味超标
甜味超标 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:35

    The accepted answer is good, but I think it could be refactored to be even better; more generic, easier to refactor and read:

    some_command_status=$(some_command && echo $? || echo $?)
    

    vs.

    some_command && some_command_status=$? || some_command_status=$?
    

提交回复
热议问题