如何获取管道中第一个命令的退出状态? [英] how to get the exit status of the first command in a pipe?

查看:49
本文介绍了如何获取管道中第一个命令的退出状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的脚本:

I made a simple script:

$ more test.bash
#!/bin/bash
echo test
exit 1

运行脚本时,退出状态应为 1

When I run the script , the exit status should be 1

$ /tmp/test.bash
echo $?
1

但是当我按以下方式运行时

But when I run this as the following

/tmp/test.bash | tr -d '\r' 1>>$LOG 2>>$LOG
echo $?
0

退出状态为 0 ,(与预期的 1 不同)

The exit status is 0, (not as expected 1)

似乎退出状态来自tr命令.但是我想要从脚本中获取退出状态-test.bash.

It seems that the exit status comes from tr command. But I what I want is to get the exit status from the script - test.bash.

为了从脚本(而不是从管道后的命令)获得正确的退出状态,我需要在语法中添加/更改什么?

What do I need to add/change in my syntax in order to get the right exit status from the script, and not from the command after the pipe line?

推荐答案

使用 PIPESTATUS 数组:

$ ls foo | cat
ls: foo: No such file or directory
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
2 0

注意: PIPESTATUS 是一种bashism(即不是POSIX).

Note: PIPESTATUS is a bashism (i.e. not POSIX).

这篇关于如何获取管道中第一个命令的退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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