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 directoryThe 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 directoryUse 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.txtMerge streams with 2>&1
2>&1 means "make descriptor 2 point where descriptor 1 points right now".
$ ls /etc/hostname nofile > all.txt 2>&1Redirections 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/hostnameThe 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
- Run
ls /etc/hostname /nopeand look at both lines. - Add
> out.txtand see which line remains on screen. - Use
2> err.txtinstead, then readerr.txt. - 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.