从子shell通过管道获取出口code [英] Get exit code from subshell through the pipes

查看:104
本文介绍了从子shell通过管道获取出口code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得的wget 退出code从子shell进程?

How can I get exit code of wget from the subshell process?

所以,主要的问题是 $?等于0,在哪里能 $?= 8 来建立?

So, main problem is that $? is equal 0. Where can $?=8 be founded?

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "$?"
0

它的工作原理,而不 T恤,其实。

$> OUT=$( wget -q "http://budueba.com/net" ); echo "$?"
8

$ {PIPESTATUS} 阵列(我不知道它是涉及到这种情况下),也并不包含该值。

But ${PIPESTATUS} array (I'm not sure it's related to that case) also does not contain that value.

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "${PIPESTATUS[1]}"    

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "${PIPESTATUS[0]}"
0

$> OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt" ); echo "${PIPESTATUS[-1]}"
0

所以,我的问题是 - 如何才能得到的wget T恤的退出code 和子shell?

如果它可能是有帮助的,我的bash的版本是 4.2.20

If it could be helpful, my bash version is 4.2.20.

推荐答案

通过使用 $()你(有效)创建一个子shell。因此,你需要看看PIPESTATUS 实例只是你的壳层内可用的(即在 $()),因为环境变量不从孩子传播到父进程。

By using $() you are (effectively) creating a subshell. Thus the PIPESTATUS instance you need to look at is only available inside your subshell (i.e. inside the $()), since environment variables do not propagate from child to parent processes.

您可以做这样的事情:

  OUT=$( wget -q "http://budueba.com/net" | tee -a "file.txt"; exit ${PIPESTATUS[0]} );
  echo $? # prints exit code of wget.

可以通过使用以下实现类似的行为:

You can achieve a similar behavior by using the following:

  OUT=$(wget -q "http://budueba.com/net")
  rc=$? # safe exit code for later
  echo "$OUT" | tee -a "file.txt"

这篇关于从子shell通过管道获取出口code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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