在bash中,我如何从一个由tee管道的函数中退出脚本? [英] In bash how do I exit a script from a function that is piped by tee?

查看:763
本文介绍了在bash中,我如何从一个由tee管道的函数中退出脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么每当我使用 function 2>& 1 |时tee -a $ LOG tee在函数中创建了一个子shell,它不能通过简单的 exit 1 退出(如果我没有使用 tee 它工作正常)。下面的例子:

 #!/ bin / bash 
LOG = / root / log.log

函数first()
{
echo函数1--我想看到这个。
exit 1
}

函数second()
{
echo函数2 - 我不想看到这个。
出口1
}
第一个2>& 1 | tee -a $ LOG
秒2>& 1 | tee -a $ LOG

输出:

  [root @ linuxbox〜]#./1.sh 
功能1 - 我想看看这个。
函数2 - 我不想看到这个。

所以。如果我删除 | tee -a $ LOG 部分,它会按预期工作(脚本将在第一个函数中退出)。



请问,解释如何克服这个问题,并在函数中能正确地退出输出?解析方案

如果你创建一个管道,函数在子shell中运行,如果您从子shell中 exit ,则只有子shell会受到影响,而不是父shell。

  printPid(){echo $ BASHPID; } 

printPid #some value
printPid #same value
printPid | tee#一个隐式的子shell - 不同的值
(printPid)#an explicit subshel​​l - 也是一个不同的值

如果不是 aFunction | tee 您可以:

  aFunction> >(tee)

它必须是相同的,除 aFunction 不会在子shell中运行,因此可以影响当前环境(设置变量,调用退出等)。

I'm trying to understand why whenever I'm using function 2>&1 | tee -a $LOG tee creates a subshell in function that can't be exited by simple exit 1 (and if I'm not using tee it works fine). Below the example:

#!/bin/bash
LOG=/root/log.log

function first()
{
echo "Function 1 - I WANT to see this."
exit 1
}

function second()
{
echo "Function 2 - I DON'T WANT to see this."
exit 1
}
first 2>&1 | tee -a $LOG
second 2>&1 | tee -a $LOG

Output:

[root@linuxbox ~]# ./1.sh  
Function 1 - I WANT to see this.
Function 2 - I DON'T WANT to see this.

So. if I remove | tee -a $LOG part, it's gonna work as expected (script will be exited in the first function).

Can you, please, explain how to overcome this and exit properly in the function while being able to tee output?

解决方案

If you create a pipeline, the function is run in a subshell, and if you exit from a subshell, only the subshell will be affected, not the parent shell.

printPid(){ echo $BASHPID; }

printPid #some value
printPid #same value
printPid | tee #an implicit subshell -- different value
( printPid ) #an explicit subshell -- also a different value

If, instead of aFunction | tee you do:

aFunction > >(tee)

it'll be essential the same, except aFunction won't run in a subshell, and thus will be able to affect the current environment (set variables, call exit, etc.).

这篇关于在bash中,我如何从一个由tee管道的函数中退出脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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