shell脚本中的异常处理?

Man*_*nde 69 bash shell exception-handling

我在shell脚本中寻找异常处理机制.有没有尝试,在shell脚本中捕获等效机制?

mde*_*ous 108

try/catchbash中没有真正的(我假设你正在使用bash),但你可以使用&&或实现一个非常相似的行为||.

在此示例中,您希望fallback_commanda_command 失败时运行(返回非零值):

a_command || fallback_command
Run Code Online (Sandbox Code Playgroud)

在本例中,second_command如果a_command 成功则要执行(返回0):

a_command && second_command
Run Code Online (Sandbox Code Playgroud)

它们可以通过使用子shell轻松混合在一起,例如,执行以下命令a_command,如果成功,它将运行other_command,但是如果a_command或者other_command失败,fallback_command将执行:

(a_command && other_command) || fallback_command
Run Code Online (Sandbox Code Playgroud)

  • Bonus:如果你想要"finally"之类的行为,请使用no-op(:in bash),如下所示:`(a_command ||:)`并且下一行将运行,好像`a_command`中没有发生错误一样. (13认同)

bri*_*cer 12

if/else结构和退出代码可以帮助你伪造一些.这应该适用于Bash或Bourne(sh).

if foo ; then
else
  e=$?        # return code from if
  if [ "${e}" -eq "1"]; then
    echo "Foo returned exit code 1"
  elif [ "${e}" -gt "1"]; then
    echo "Foo returned BAD exit code ${e}"
  fi
fi
Run Code Online (Sandbox Code Playgroud)

  • @jiliagre这不起作用."!foo"反转$?从0到1和!0到0. (2认同)

小智 5

    {
        # command which may fail and give an error 
    } || {
       # command which should be run instead of the above failing      command
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果您向问这个问题的人解释,您发布的伪代码,而不只是他们可能不理解的一部分密码,可能会更好。如果孩子听不懂,那不是一个好答案。 (2认同)