通过管道从子shell获取退出代码

ДМИ*_*КОВ 13 bash pipe exit-code tee subshell

如何wget从子shell进程获取退出代码?

所以,主要问题是$?等于0.哪里可以$?=8建立?

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

tee实际上它没有用.

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

但是${PIPESTATUS}数组(我不确定它与那种情况有关)也不包含该值.

$> 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
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是 - 如何wget通过tee子shell 获取退出代码?

如果它可能有用,我的bash版本是4.2.20.

Chr*_*n.K 16

通过使用$()你(有效地)创建一个子shell.因此,PIPESTATUS您需要查看的实例仅在子shell(即内部$())中可用,因为环境变量不会从子进程传播到父进程.

你可以这样做:

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

您可以使用以下方法实现类似的行为:

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

  • 这不是[`export`](http://www.gnu.org/software/bash/manual/bashref.html#Environment)的工作方式-它将变量作为*子*进程(从父进程)导出为环境变量。 (2认同)

Mrs*_*man 5

使用local变量时要注意这一点:

local OUT=$(command; exit 1)
echo $? # 0

OUT=$(command; exit 1)
echo $? # 1
Run Code Online (Sandbox Code Playgroud)

  • 声明`local OUT`然后在新行上分配`OUT =`正确设置退出代码变量`$?`如果你不想要范围蠕变. (5认同)