【发布时间】:2015-12-20 21:07:52
【问题描述】:
我试图理解为什么每当我使用function 2>&1 | tee -a $LOG tee 时会在函数中创建一个子shell,而该子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中执行(最后一个取决于选项或其他东西——我忘了)。为什么?因为。至于如何正确退出,请查看退出状态(如果设置了
pipefail)或管道后的PIPESTATUS。 -
以上评论的跟进:我忘记的选项是
lastpipe。 -
4ae1e1,也谢谢你。在您的帮助下,我还了解了 PIPESTATUS,显然是解决方法:
function PIPE_STAT() { if [[ $PIPESTATUS -ne 0 ]]; then exit 1 fi }可以使用并放置在每个function 2>&1 | tee -a $LOG之后以验证状态并在需要时退出。
标签: bash function exit tee subshell