🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Errors and Redirection

Errors go to a separate stream called stderr. Normal output goes to stdout, and the two streams can go to different places.

Errors are separate

The error message appears, but it is not normal output. The output below shows only the normal output.

ls missing.txt
echo done

Send errors to a file

2> sends the error message into errors.txt, and cat prints it.

ls missing.txt 2> errors.txt
cat errors.txt

Join errors with output

2>&1 sends the error message to the same place as normal output.

ls missing.txt 2>&1
echo done

Throw errors away

/dev/null throws the error message away, so only done prints.

ls missing.txt 2> /dev/null
echo done

Example

ls missing.txt 2> errors.txt
ls notes.txt > /dev/null 2>> errors.txt
cat errors.txt
echo done

Key points

  • stdout: the stream for normal output.
  • stderr: the stream for error messages.
  • Use 2> file to send errors into a file.
  • Use 2>&1 to join errors with normal output.
  • /dev/null: a place that throws away anything sent to it.

In this example, the first ls sends its error into errors.txt. The second ls finds notes.txt, so it adds no error. Then cat prints the error from the file. Last echo prints done.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which part sends errors into a file?