给定一个命令,其输出正由 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
以大致相同的方式失败。
为什么不直接使用一个函数:
#!/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)
这会将整个结果发送到日志文件,然后将数据回显到标准输入,您可以在其中根据需要捕获它。