我需要帮助将输出(stdin和stdout)从系统命令发送到bash函数,同时仍然接受参数的输入.像下面的例子.有人可以指出我正确的道路吗?
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)
为此,您可以使用
原文链接:https://www.f2er.com/bash/386822.htmlread
bash内置:
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
更新:
为了能够使用stdin或一个参数作为输入(根据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 }