Skip to main content
In this lesson, we dive into advanced mechanics of standard output (stdout) and standard error (stderr) in Bash. Building on basic shell scripting, mastering these streams—especially when paired with redirection and pipelines—is essential for robust, complex scripts.
The image is a graphic titled "Stdout and Stderr," featuring icons and text related to mastering complex shell scripting, with labels for "Standard out" and "Standard error."

What Are Stdout and Stderr?

When you execute a command, it sends data to:
  • Standard Output (stdout): the default channel for normal output.
  • Standard Error (stderr): the default channel for error and diagnostic messages.
Both streams appear in your terminal by default, but they serve different purposes. Think of them as two separate pipes under your sink: clean water (stdout) versus wastewater (stderr). Keeping them distinct helps you handle success and failure conditions independently.

Examples of Stdout vs. Stderr

A simple ls shows stdout:
With a long listing format (-l):
If you pass an invalid flag (-j), it emits stderr:
Not all commands print to stdout by default. For example, mv works silently unless you use -v:
If mv can’t find a file, it writes to stderr:
Separating stdout and stderr allows you to log normal output separately from errors, making debugging and automation much cleaner.

Redirecting Stdout and Stderr

By default, > captures only stdout. To see how this works, consider redirecting the output of an echo:
The image explains how to separate standard output and standard error using redirection symbols, specifically the "greater than" and "double greater than" symbols.

Redirecting stderr

To catch error messages, prefix the redirection operator with 2 (stderr’s file descriptor):
The image explains that the redirection symbol is designed to redirect only standard output by default and can only catch standard output streams when used alone.
Now, the invalid-option error goes into errors.txt while stdout (if any) stays on the terminal.

File Descriptors and Redirection Table

Linux assigns numeric file descriptors to each stream:

Separating Both Streams

To send stdout and stderr to different files:
Or, when a command succeeds:

Combining Streams

Merge stderr into stdout, writing both to the same file or pipe:
Using > will overwrite existing files. To avoid data loss, double-check your redirections or use >> to append.

See Also

References

Watch Video