根据进程退出码退出Shell脚本 [英] Exit Shell Script Based on Process Exit Code

查看:47
本文介绍了根据进程退出码退出Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行许多命令的 shell 脚本.如果任何命令以非零退出代码退出,我如何让 shell 脚本退出?

I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?

推荐答案

在每个命令之后,可以在 $? 变量中找到退出代码,所以你会得到类似的东西:

After each command, the exit code can be found in the $? variable so you would have something like:

ls -al file.ext
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

你需要小心管道命令,因为 $? 只给你管道中最后一个元素的返回码,所以,在代码中:

You need to be careful of piped commands since the $? only gives you the return code of the last element in the pipe so, in the code:

ls -al file.ext | sed 's/^/xx: /"

如果文件不存在,则不会返回错误代码(因为管道的 sed 部分实际上可以工作,返回 0).

will not return an error code if the file doesn't exist (since the sed part of the pipeline actually works, returning 0).

bash shell 实际上提供了一个可以在这种情况下提供帮助的数组,即 PIPESTATUS.该数组为每个管道组件都有一个元素,您可以像 ${PIPESTATUS[0]} 一样单独访问这些元素:

The bash shell actually provides an array which can assist in that case, that being PIPESTATUS. This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]}:

pax> false | true ; echo ${PIPESTATUS[0]}
1

请注意,这是为您提供 false 命令的结果,而不是整个管道.您还可以根据需要处理整个列表:

Note that this is getting you the result of the false command, not the entire pipeline. You can also get the entire list to process as you see fit:

pax> false | true | false; echo ${PIPESTATUS[*]}
1 0 1

如果您想从管道中获取最大的错误代码,您可以使用以下方法:

If you wanted to get the largest error code from a pipeline, you could use something like:

true | true | false | true | false
rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done
echo $rc

这会依次遍历每个 PIPESTATUS 元素,如果它大于之前的 rc 值,则将其存储在 rc 中.

This goes through each of the PIPESTATUS elements in turn, storing it in rc if it was greater than the previous rc value.

这篇关于根据进程退出码退出Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆