Sample Header Ad - 728x90

tee /dev/stderr inside script truncates output file if you redirect stderr

2 votes
2 answers
285 views
Given a script like below if I try to redirect stderr to a file, then the file is truncated at the point tee is used:
$ cat test.sh 
#!/bin/bash

set -eux
echo before
echo '{ "foo": "bar" }' | tee /dev/stderr | jq .foo
echo after
$ ./test.sh 2> log
before
"bar"
after
$ cat log 
{ "foo": "bar" }
+ echo after
The log file should have all of the stderr output. Everything I see if I run the same script without redirecting:
$ ./test.sh
+ echo before
before
+ echo '{ "foo": "bar" }'
+ tee /dev/stderr
+ jq .foo
{ "foo": "bar" }
"bar"
+ echo after
after
So why do I only see the lines that come _after_ tee? Using 2>> doesn't seem to help. I Don't understand why is this happening. How can I tee the output while still having the ability to redirect the whole script stderr to a file?
Asked by Jakub Bochenski (325 rep)
Oct 13, 2023, 05:06 PM
Last activity: Oct 13, 2023, 09:55 PM