Skip to content

Understanding stdout, stderr, and Redirection in Linux

1. Standard Streams

In Unix-like systems, every process starts with three standard I/O streams:

Name File Descriptor Purpose
stdin 0 Standard input
stdout 1 Standard output
stderr 2 Standard error output

Sources:

  • The Open Group Base Specifications Issue 7 (2024 Edition), “File Descriptors”.
  • GNU C Library Reference Manual, “Standard Streams”.

2. What is stdout?

stdout (file descriptor 1) is used for normal program output.

Example:

ls
This prints filenames to stdout.


3. What is stderr?

stderr (file descriptor 2) is used for error messages and diagnostics.

Example:

ls /does_not_exist
This prints an error message to stderr, not stdout.


4. Why stdout and stderr are separated

Separating them allows: - Redirecting normal output to a file - Keeping errors visible on the terminal - Or redirecting both if needed


5. Redirecting stdout

command > file.txt

This sends stdout → file.txt.


6. Redirecting stderr

command 2> errors.txt

This sends stderr → errors.txt.


7. Redirecting stdout and stderr together

To send both stdout and stderr to the same file:

command > output.txt 2>&1

Explanation: - > redirects stdout - 2>&1 makes stderr go to the same destination as stdout

This is commonly used in cron jobs to collect all output in a single log file.


8. Example

ls /tmp /does_not_exist > all_output.log 2>&1

Result: - Normal /tmp listing and the error message both go into all_output.log.


9. Summary

  • stdout = normal output
  • stderr = error output
  • They can be redirected separately or together
  • 2>&1 redirects stderr into stdout's destination