我试图理解为什么每当我使用 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/