gpt4 book ai didi

bash - 将 stdout 和 stderr 重定向到函数

转载 作者:行者123 更新时间:2023-11-29 08:45:52 24 4
gpt4 key购买 nike

我需要帮助将输出(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

更新:

为了能够使用标准输入或参数作为输入(根据 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
}

关于bash - 将 stdout 和 stderr 重定向到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11904907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com