基于进程退出code出口Shell脚本 [英] Exit Shell Script Based on Process Exit Code

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

问题描述

我有一个执行一些命令shell脚本。如何让我的shell脚本退出,如果任何命令退出与非零退出code的?

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?

推荐答案

每个命令后,退出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

您需要小心的管道命令,因为 $?只给你在管道的最后一个元素返回code左右,在code:

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: /"

将不会返回错误code。如果文件不存在(因为管道 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).

庆典外壳实际上提供了一个数组,可以帮助在这种情况下,这是 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

请注意,这是得到你的命令,而不是整个管道的结果。您还可以得到整个列表来处理您认为合适的:

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

如果你想从管道获得最大的错误code,你可以使用类似:

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 ,如果它比越大previous RC 值。

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

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

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