2012-08-10 174 views
16

我需要帮助将系统命令的输出(stdin和stdout)发送到bash函数,同时仍接受来自参数的输入。就像下面的例子。有人能把我指向正确的道路吗?将stdout和stderr重定向到函数

LogMsg() 
{ 
    DateTime=`date "+%Y/%m/%d %H:%M:%S"` 
    echo '*****'$DateTime' ('$QMAKESPEC'): '$1 >> "$LogFile" 
    echo $DateTime' ('$QMAKESPEC'): '$1 
} 

# Already works 
LogMsg "This statement is sent directly" 

# Wish I could do this: 
# Capture both stdout & stderr of a system function to the logfile 
# I do not presume that any of the syntax that follows is good 
make 2>&1 >(LogMsg) 
+0

你仍然要调用'LogMsg'用命令行参数的能力吗? – chepner 2012-08-10 16:42:19

回答

13

要做到这一点,你可以使用bash的read内置:

LogMsg() 
{ 
    read IN # This reads a string from stdin and stores it in a variable called IN 
    DateTime=`date "+%Y/%m/%d %H:%M:%S"` 
    echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile" 
    echo $DateTime' ('$QMAKESPEC'): '$IN 
} 

然后用管:

make 2>&1 | LogMsg 

更新:

为了能够使用标准输入或参数作为输入(按chepner的评论),你可以这样做:

LogMsg() 
{ 
    if [ -n "$1" ] 
    then 
     IN="$1" 
    else 
     read IN # This reads a string from stdin and stores it in a variable called IN 
    fi 

    DateTime=`date "+%Y/%m/%d %H:%M:%S"` 
    echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile" 
    echo $DateTime' ('$QMAKESPEC'): '$IN 
} 
+2

这种方法唯一的问题是你不能在不证明标准输入的情况下调用LogMsg。目前还不清楚瑞恩是否想要这种灵活性。 – chepner 2012-08-10 16:46:06

+0

@chepner:好点。我已经相应地更新了答案。 – 2012-08-10 16:56:55

+0

是的灵活性是我想要的,我应该更清楚。 – Ryan 2012-08-10 16:58:17

-2

有2种方式这样做的, 第一,我认为这是更好的,是创建一个bash文件,并将结果传递给它这样的:

make 2>&1 > ./LogMsg 

第二种方式是通过结果作为参数传递给函数:

LogMsg $(make 2>&1) 
+1

你的第一个选择不清楚。你的意思是把make的输出传给'LogMsg'(它不能像写入的那样从标准输入读取)?你的第二个选项只会处理make的第一行,因为'LogMsg'只处理它的第一个参数。 – chepner 2012-08-10 16:54:06

-1

在我看来,读取命令的超时时间为100ms(-t 0.1)将允许LogMsg处理输入管道和参数在没有输入的情况下永远等待。

function log(){ read -t 0.1 IN1 
    echo $(date "+%Y/%m/%d %H:%M:%S")' ('$QMAKESPEC'): '$IN1 $* |tee -a $LogFile ;} 
#test without, with pipe , with pipe and parameters , with parameters only 
log ; echo foo | log ; echo foo | log bar ; log bar 
2015/01/01 16:52:17(): 
2015/01/01 16:52:17(): foo 
2015/01/01 16:52:17(): foo bar 
2015/01/01 16:52:17(): bar 

发球-a复制到标准输出,并追加到$ LOGFILE

乐趣

相关问题