如何在要读取的ksh函数中打印日志消息?

时间:2018-08-30 06:31:06

标签: ksh

说我有一个功能:

function doSomeWork
{
    #work, work, work
    echo "$result1 $result2"
}

现在我正在使用read读取该函数的结果:

doSomeWork | read r1 r2
echo "result1: r1, result2: r2"

这很好用,但是现在我无法使用echo输出任何其他日志消息,因为它将使结果读取变糟。

如何在doSomeWork中编写日志消息而不干扰读取?


编辑:这里是该方法的演示

#!/bin/ksh
echo "7 54" | read T1 T2
echo "T1 $T1 T2 $T2"

2 个答案:

答案 0 :(得分:3)

另一种可能性是使用命名管道(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

如果您有许多函数调用,则只需创建/销毁管道一次。

答案 1 :(得分:2)

您可以将其他日志消息写入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}"