bash – 将stdout和stderr重定向到Function
发布时间:2020-12-15 18:56:17 所属栏目:安全 来源:网络整理
导读:我需要帮助将输出(stdin和stdout)从系统命令发送到bash函数,同时仍然接受参数的输入.像下面的例子.有人可以指出我正确的道路吗? LogMsg(){ DateTime=`date "+%Y/%m/%d %H:%M:%S"` echo '*****'$DateTime' ('$QMAKESPEC'): '$1 "$LogFile" echo $DateTime' (
我需要帮助将输出(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)
为此,您可以使用
read 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |