Bash Separating Standard Error
Separating standard error is the practice of sending error output to a different place than normal output. Separation keeps results clean while errors stay visible and countable.
Stdout and stderr land in different files
Normal output goes to one file and the error from a missing file goes to another. Each file holds only its own stream.
echo "good result" > out.txt
cat missing.txt 2> err.txt
echo "out file:"
cat out.txt
echo "err file:"
cat err.txtA separate error file can be counted
Good lines print as normal output, while the error is trapped in its own file. The count line proves the error was kept apart.
printf 'ok one\nok two\n' > good.txt
cat good.txt
cat missing.txt 2> errors.txt
echo "error lines: $(grep -c . errors.txt)"
cat errors.txtRedirection order decides where stderr goes
In the first order, stderr escapes to the terminal and the file holds only stdout. In the second order, both streams land in the file.
emit() {
echo "to stdout"
echo "to stderr" >&2
}
echo "order A file:"
emit 2>&1 > first.txt
cat first.txt
echo "order B file:"
emit > second.txt 2>&1
cat second.txtExample
printf 'alpha\n' > good.txt
run_checks() {
cat good.txt
cat missing.txt 2>errors.txt
echo "checks done"
}
run_checks > results.txt
echo "results:"
cat results.txt
echo "errors:"
cat errors.txt
echo "error count: $(grep -c . errors.txt)"Key points
- Separate streams: send stdout to one file and stderr to another with two redirections.
- Order rule: in >file 2>&1, stderr follows stdout to the same file, while in 2>&1 >file, stderr stays on the terminal.
- Clean stdout: keeping errors out of stdout lets later tools read only real results.
- Count errors: a separate error file can be counted without mixing error text into results.
- Silence with care: sending stderr to /dev/null hides noise, but it also hides real errors.
- Merge last: merge streams only after you no longer need them apart.
In this example, run_checks prints a good line and a done line, while the missing-file error is redirected to its own file. The whole function output goes to the results file, but the inner redirection keeps the error apart. The final lines show the clean results, the error, and its count.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does `cmd >file 2>&1` do that `cmd 2>&1 >file` does not?