【问题标题】:Exit status of tee>(...)tee>(...) 的退出状态
【发布时间】:2014-04-14 21:03:14
【问题描述】:

我正在执行:

Command1 | tee >(grep sth) || Command2 

我希望 Command2 根据 grep 的退出状态执行,而在当前配置中它是根据 tee。

据我所知 pipefail 和 pipestatus 在这里不起作用(如果我错了,请纠正我)。

根据 Alexej Answer 修改 Origian 问题

我也尝试了Command1 | tee >(grep sth || Command2),它适用于我原来的问题,但是当我试图在子shell中设置我的测试状态时;例如,Command 1 | tee>(grep sth || Result="PASSED") 及以后可以访问我代码的其他块中的 Result。所以我还是有问题。

谢谢

【问题讨论】:

  • command1 | tee | grep sth 不起作用吗?有什么理由需要使用 subshel​​l?
  • 我需要记录“Command1”的输出以及“grep”的输出(一些设备测试要求)。通过使用管道,我无法记录“Command1”的输出。另一种方法是执行 Command1,记录输出,然后第二次执行它并将其通过管道传输到 grep,这很难看 :)。 "command1 | tee | grep sth" 将标准输出重定向到 grep。这是我的第一个问题stackoverflow.com/questions/23066559/… 导致我使用 subshel​​l 和 ....
  • 好的,你是说if (command1 | tee | grep sth &> /dev/null); then command2; fi 对吧?

标签: tee subshell exitstatus


【解决方案1】:

将您的脚本更改为:

Command1 | tee >(grep sth || Command2)

达到预期的效果。

关于 Subshel​​ls 的一句话

>(....) 是一个子shell。您在该子shell 中所做的任何事情(除了所述子shell 的退出状态)都完全 与外界隔离:(a=1); echo $a 永远不会回显数字1,因为a 只有在定义它的子shell中有意义。

我不完全明白为什么,但是当你重定向到子shell时,它似乎反转了该子shell的退出状态,因此失败将返回true,成功将返回false。

echo 'a' >(grep 'b') && echo false
# false
(exit 1) || echo false
# false

所以如果我的第一个建议不适合你,那么试着重写你的脚本:

Command1 | tee >(grep sth) && Command2

一个例子

a=1 # `a` now equals `1`
# if I run `exit`, $a will go out of scope and the terminal I'm in might exit
(exit) # $a doesn't go out of scope because `exit` was run from within a subshell.
echo $a # $a still equals `1`

您可以在哪里了解有关子外壳的更多信息

Set a parent shell's variable from a subshell
Pass variable from a child to parent in KSH
Variables value gets lost in subshell
http://www.tldp.org/LDP/abs/html/subshells.html
http://mywiki.wooledge.org/SubShell
http://wiki.bash-hackers.org/syntax/expansion/proc_subst

【讨论】:

  • 我还有一些问题:Coomand1 | tee >(grep sth || Command2) 效果很好,但是 Coomand1 | tee >(grep sth || var1=sth) 不起作用。是否有任何原因我无法在此配置中分配参数。
  • “我无法在此配置中分配参数...”是什么意思?你的意思是它运行得很好,但是你不能访问变量?
  • 假设我分配了 {var1=2},然后我运行 {Command1 | tee >(grep sth || var1=3)} (Command | tee >(grep sth) 退出状态为 0)。后来,我检查 $var1 仍然是 2,而它应该是 3。
  • @Aman 我已经更新了我的答案以解决您遇到的变量问题。
  • 谢谢,我也更新了这个问题(根据你的回答),因为我还在努力解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
相关资源
最近更新 更多