bash脚本:如何保存第一个命令的返回值在管道? [英] bash script: how to save return value of first command in a pipeline?

查看:283
本文介绍了bash脚本:如何保存第一个命令的返回值在管道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

击:我想运行一个命令和管道通过一些过滤的结果,但如果命令失败,我想回到命令的误差值,而不是过滤器的无聊的返回值:

Bash: I want to run a command and pipe the results through some filter, but if the command fails, I want to return the command's error value, not the boring return value of the filter:

例如:

if !(cool_command | output_filter); then handle_the_error; fi

或者

set -e
cool_command | output_filter

在这两种情况下的 cool_command 的返回值,我关心的 - 在第一种情况下的如果条件,或在第二次退出脚本案例。

In either case it's the return value of cool_command that I care about -- for the 'if' condition in the first case, or to exit the script in the second case.

有一些干净的成语这样做?

Is there some clean idiom for doing this?

推荐答案

使用 PIPESTATUS 内建变量。

男人庆典

PIPESTATUS

这是数组变量(见阵列
  下文)含有出口的列表
  从在过程状态值
  最-最近执行的前台
  管线(其可以仅包含一个
  单指令)。

An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

这篇关于bash脚本:如何保存第一个命令的返回值在管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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