2014-09-05 115 views
0

我是bash shell脚本编写新手,面临一个问题。Bash变量值未设置

我有这样的代码:

function build() 
{ 

    echo "Building: " | tee -a $LOG_FILE 
    { 
     #do some processing here and if error set the err var to say 2 
     if [[ $err -eq 2 ]]; then 
      echo "Error: exit" 
      exitStatus=2 
     fi 
    } 2>&1 | tee -a $LOG_FILE | grep -e "$GREP_FAIL_TERM" -e "$GREP_ERROR_TERM" 
} 

其中

GREP_FAIL_TERM='[Ff]ail' 
GREP_ERROR_TERM='[Ee][Rr][Rr][Oo][Rr][,;:\ ]' 

exitStatus is a global variable set to 0 at the beginning of script 

当我在错误的情况下走出这个功能,并检查退出状态的值它是0. 我读到使用|在子窗体中执行不在父项中反映的命令。 但是,如何在输出到日志文件时执行上面的代码。

+0

真的!!没有得到你的问题。 – 2014-09-05 11:36:49

+1

管道引入子壳。子shell不能在父shell中设置变量,所以'exitStatus'不能转义子shell。 – 2014-09-05 13:10:05

回答

0

是的,这是一个困难的情况。

最简单的方法是将标记放入子shell脚本的输出中,并根据它们的存在确定状态。

你的grep已经出错了(尽管grep -i会是你的好朋友)。返回代码应该向你指出错误。

function build() 
{ 
    { 
     echo "Building: " 
     # do stuff 
    } 2>&1 | tee -a $LOG_FILE | grep -Ei "fail|error[,;: ]" 
    SUCCESS=$? # 0 if an error was detected 
}