Skip to content

Linux Foundations / Find your way around Linux ยท Step 33 of 63

Lesson: stderr (Standard Error)Switch
โ† Linux Foundations

Shell and files

stderr (Standard Error)

Learn how error messages travel separately and how to redirect, merge or discard them.

Programs have a second output channel for error messages and diagnostics, called standard error, or stderr. It is file descriptor 2.

Why a separate channel

Ask ls for a file that does not exist and save the output:

$ ls nofile > out.txt
ls: cannot access 'nofile': No such file or directory

The message still appears on screen and out.txt is empty. > redirects only stdout, while the complaint went to stderr. This keeps errors from slipping unnoticed into your data. The exact wording of messages varies between systems.

Redirect errors with 2>

Put the descriptor number directly before the operator, with no space.

$ ls nofile 2> errors.txt
$ cat errors.txt
ls: cannot access 'nofile': No such file or directory

Use 2>> to append instead of overwrite. If you write 2 >, the shell treats 2 as an ordinary argument and redirects stdout.

You can split the two streams into separate files:

$ ls /etc/hostname nofile > found.txt 2> errors.txt

Merge streams with 2>&1

2>&1 means "make descriptor 2 point where descriptor 1 points right now".

$ ls /etc/hostname nofile > all.txt 2>&1

Redirections are processed from left to right, so order matters. Here stdout goes to the file first, then stderr copies it, and both land in all.txt.

Reverse them with 2>&1 > all.txt and stderr copies the old stdout, which is the terminal. Errors stay on screen and only normal output reaches the file.

Bash offers the shortcut &> all.txt for the same merge, and &>> all.txt to append (Bash 4 or later). Plain POSIX sh does not, so use > all.txt 2>&1 in portable scripts.

Throw output away

/dev/null is a special file that discards everything written to it.

$ ls /etc/hostname nofile 2> /dev/null
/etc/hostname

The error is hidden, but the command still failed. Its exit status, shown by echo $?, is not zero. Hide errors only when you know which ones you expect.

The streams and text lab lets you try these on a live system.

Try it

  1. Run ls /etc/hostname /nope and look at both lines.
  2. Add > out.txt and see which line remains on screen.
  3. Use 2> err.txt instead, then read err.txt.
  4. Capture both with > all.txt 2>&1.

Check your understanding

stderr (Standard Error)

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.