且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据进程退出码退出Shell脚本

更新时间:2023-12-05 21:10:34

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

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.