当 stdout 重定向到文件时,将消耗的输出复制到 stdout

ajo*_*org 6 bash io

给定一个命令,其输出正由 grep 处理,我还希望将实际输出包含在日志文件中以进行调试。

例如,如果我有以下内容

useful=$(curl -s http://example.com/some/data | grep 'useful line')
echo "useful=$useful"
Run Code Online (Sandbox Code Playgroud)

我想看看

This page has a number of lines in it, but'
useful lines are the only ones I care about
except when something goes wrong and then
I'd really like to see what the heck was in
the output that grep consumed.
useful=useful lines are the only ones I care about
Run Code Online (Sandbox Code Playgroud)

可以像这样用 T 恤完成

useful=$(curl -s http://example.com/some/data | tee /proc/$$/fd/1 | grep 'useful line')
echo "useful=$useful"
Run Code Online (Sandbox Code Playgroud)

但是如果标准输出被重定向到一个文件,tee则会破坏日志文件的其余部分。tee -a以大致相同的方式失败。

Old*_*mer 0

为什么不直接使用一个函数:

#!/bin/bash
logAndEcho () {
    echo -e "$@" >> LOGFILE.txt
    echo -e "$@"
}
var=$(logAndEcho "one\ntwo\nThis is a test"|grep one)
echo "var=$var"
Run Code Online (Sandbox Code Playgroud)

这会将整个结果发送到日志文件,然后将数据回显到标准输入,您可以在其中根据需要捕获它。