说我有一个功能:
function doSomeWork
{
#work, work, work
echo "$result1 $result2"
}
现在我正在阅读该函数的结果,使用如下所示:
doSomeWork | read r1 r2
echo "result1: r1, result2: r2"
这很好用,但现在我不能使用echo输出任何其他日志消息,因为它会搞砸读取结果。
如何在不干扰读取的情况下在doSomeWork中编写日志消息?
编辑:这里是该方法的演示
#!/bin/ksh
echo "7 54" | read T1 T2
echo "T1 $T1 T2 $T2"
另一种可能性是使用命名管道(FIFO)而不是匿名管道。并不总是正确的解决方案,但也许它会给你一些想法:
pipe_name=/tmp/mypipe$$
mkfifo "$pipe_name"
function doSomeWork
{
result1='result1'
result2='result2'
echo "work, work, work"
echo "$result1 $result2" > "$pipe_name"
}
doSomeWork & # running in background, otherwise it would block
read r1 r2 < "$pipe_name"
echo "result1: r1, result2: r2"
rm "$pipe_name"
得到:
work, work, work
result1: r1, result2: r2
如果您有许多函数调用,那么您只需创建/销毁一次管道。
您可以将其他日志消息写入stderr。另一种解决方案是确保可以过滤输出:
用尾巴
function doSomeWork
{
echo "work, work, work"
result1=1
result2=2
echo "More work"
echo "$result1 $result2"
}
doSomeWork | tail -1 | read r1 r2
echo "result1: ${r1}, result2: ${r2}"
用grep
function doSomeWork
{
echo "work, work, work"
result1=1
result2=2
echo "More work"
echo "Result $result1 $result2"
}
doSomeWork | grep Result | read dummy r1 r2
echo "result1: ${r1}, result2: ${r2}"