I’ve got approximately the following code:

cat infile | while read line; do
    echo 2> 'log ' $line
    echo $line
done > outfile

outfile is created correctly. However, the STDERR output just vanished: it’s neither displayed on the terminal nor in outfile. If I replace the last line above with done > outfile 2> errfile then errfile is created, but empty.

Can I capture the error output from within the loop, preferably by streaming it directly into the parent STDERR (the above is part of a larger script whose standard error stream is captured by yet another process)?


Your syntax is wrong: it should be >&2 not 2>.


Your example doesn't work because inside the loop you are redirecting stderr with 2>. And then when you try to redirect it again outside the loop there is nothing left in the stream to redirect.

It would seem that this is what you actually wanted to do:

cat infile | while read line; do
    echo >&2 'log ' $line
    echo $line
done > outfile 2> errfile

This should redirect all errors from inside the while loop as expected. Unless you have already redirected errors inside the loop, as the example in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.