linux 在bash中忽略特定退出代码的最佳方法

63lcw9qa  于 4个月前  发布在  Linux
关注(0)|答案(1)|浏览(46)

举个例子

timeout my_cmd
# if the command is failed due to timeout, aka exit code is 124,
# then the script should contiune to run other commands,
# otherwise it should stop.
# And what if there is more exit code to ignore?
other_cmds

字符串
我想我可能会检查$?来控制运行流,但我想知道在Linux中是否有任何针对此模式的既定方法。

2o7dmzc5

2o7dmzc51#

继续我的评论,在timeout my_cmd之后添加:

timeout my_cmd

ecode="$?"     # save the exit code

# if exit code is not 124, then advise the user and exit
if [ "$ecode" -ne 124 ]; then 
  printf "exit code '%s' - exiting.\n" "$ecode"
  exit "$ecode"
fi

other commands

字符串
如果退出代码为124,脚本将继续运行,但对于其他所有退出代码,则使用正确的退出代码退出。如果有问题,请告诉我。
如果你想检查多个退出代码,那么@CharlesDuffy提供的case语句是最好的方法。他建议case $ecode in 124|125) :;; *) exit "$ecode";; esac适合你的需求。简而言之,如果124125执行:(无操作,无),对于每一个其他退出代码执行*(默认)case和exit
举例来说:

# if exit code is not 124 or 125, then advise the user and exit
case "$ecode" in
  124|125 ):;;
  * ) 
  printf "exit code '%s' - exiting.\n" "$ecode"
  exit "$ecode";;
esac


你也可以使用一个if和旧的语法,并否定组合检查来完成同样的事情,例如,你可以写if语句:

# if exit code is not 124 or 125, then advise the user and exit
if ! [ "$ecode" -eq 124 -o "$ecode" -eq 125 ]; then 
  printf "exit code '%s' - exiting.\n" "$ecode"
  exit "$ecode"
fi


然后,它将按照您的期望执行,但请注意,使用-o-a的测试组合是一种较旧的方法,与||&&语法相比并不受欢迎-但这里确实提供了一个解决方案。

相关问题