我需要帮助将输出(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)
Run Code Online (Sandbox Code Playgroud)
Lee*_*ton 14
要做到这一点,你可以使用readbash内置:
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
}
Run Code Online (Sandbox Code Playgroud)
然后使用管道:
make 2>&1 | LogMsg
Run Code Online (Sandbox Code Playgroud)
更新:
为了能够使用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
}
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个旧线程..但我用它来帮助我编写一个日志函数,该函数还将输出多行命令输出:
# Defines function to grab a time stamp #
get_Time () { Time=$(date +%Y-%m-%d\ %H:%M:%S) ; }
write_Log()
{
get_Time
if [ -n "${1}" ]; then # If it's from a "<message>" then set it
IN="${1}"
echo "${Time} ${IN}" | tee -a ${log_File}
else
while read IN # If it is output from command then loop it
do
echo "${Time} ${IN}" | tee -a ${log_File}
done
fi
}
Run Code Online (Sandbox Code Playgroud)