stdoutがファイルにリダイレクトされると、消費された出力をstdoutにコピーします。

stdoutがファイルにリダイレクトされると、消費された出力をstdoutにコピーします。

grepのように出力を処理するコマンドが与えられたら、デバッグ目的で実際の出力をログファイルに含めたいと思います。

たとえば、次のような場合

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

見たい

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

これできるTシャツはこんな感じです

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

しかし、stdoutがファイルにリダイレクトされると、teeログファイルの残りの部分が破損します。tee -aほぼ同じ方法で失敗します。

ベストアンサー1

teestdout制御端末装置への流れ/dev/tty

(
exec 1> >(tee -a stdout.log)
: > stdout.log
#var="$(echo -e "one\ntwo" | tee /dev/tty | grep one)"
var="$(echo -e "one\ntwo" | tee -a /dev/tty stdout.log | grep one)"
echo "var=$var"
)

cat stdout.log
# one
# two
# var=one

おすすめ記事