簡體   English   中英

在bash中如何從tee管道的函數中退出腳本?

[英]In bash how do I exit a script from a function that is piped by tee?

我試圖理解為什么每當我使用function 2>&1 | tee -a $LOG 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 -a $LOG部分,它將按預期工作(腳本將在第一個函數中退出)。

請您解釋一下如何克服這個問題,並在功能輸出時正確退出?

如果創建管道,則該函數在子shell中運行,如果從子shell exit ,則只會影響子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 > >(tee)

它將是必不可少的,除了aFunction不會在子shell中運行,因此將能夠影響當前環境(設置變量,調用退出等)。

使用PIPESTATUS檢索管道中第一個命令的退出狀態。

first 2>&1 | tee -a $LOG; test ${PIPESTATUS[0]} -eq 0 || exit ${PIPESTATUS[0]}
second 2>&1 | tee -a $LOG; test ${PIPESTATUS[0]} -eq 0 || exit ${PIPESTATUS[0]}

如果管道中的任何內容因set -e -o pipefail失敗,您可以告訴bash失敗:

$ cat test.sh
#!/bin/bash
LOG=~/log.log

set -e -o pipefail

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
$ ./test.sh
Function 1 - I WANT to see this.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM