bash - 在 bash 中,如何从由 tee 传输的函数中退出脚本?

标签 bash function exit tee subshell

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

#!/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

输出:

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

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

能否请您解释一下如何克服这个问题并在函数中正确退出,同时能够输出 tee?

最佳答案

如果您创建一个管道,该函数在子 shell 中运行,如果您从子 shell 退出,则只有子 shell 会受到影响,而不会影响父 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

如果,而不是 aFunction | tee 你做的:

aFunction > >(tee)

本质上是一样的,除了 aFunction 不会在子 shell 中运行,因此将能够影响当前环境(设置变量、调用退出等)。

关于bash - 在 bash 中,如何从由 tee 传输的函数中退出脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385862/

相关文章:

function - 调用函数时将函数用作成员的内存成本

c - 了解有关 c 中退出函数的一行

docker - 如何知道 docker 容器退出的原因?

linux - 如何使用 collectd 在 linux 中将系统指标从一台机器推送到另一台机器?

bash - 紧急覆盖 bash 中损坏的命令完成?

java - 使用Java程序填写Git凭证

python - 如何将数据框中每个组中的行转换为列?

linux - 查找具有(或没有)特定所有者的文件

C# Unity - 确定哪个方法正在影响游戏对象

c - 如果在C中退出(exitcode)会发生内存泄漏?