我试图理解为什么每当我使用function 2>&1 | tee -a $LOG
tee 在函数中创建一个无法通过简单退出的子 shellexit 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
Output:
[root@linuxbox ~]# ./1.sh
Function 1 - I WANT to see this.
Function 2 - I DON'T WANT to see this.
所以。如果我删除| tee -a $LOG
部分,它将按预期工作(脚本将在第一个函数中退出)。
您能否解释一下如何克服这个问题并在函数中正确退出,同时能够输出?
如果您创建管道,该函数将在子 shell 中运行,并且如果您exit
从子 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
you do:
aFunction > >(tee)
本质上是一样的,除了aFunction
不会在子 shell 中运行,因此能够影响当前环境(设置变量、调用退出等)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)