Redirecting Errors with 2>
The operator 2> sends standard error, the channel that carries error messages, to a file. Because standard error is separate from standard output, you can keep a log of problems, hide harmless noise, or store results and errors in different files. This is one of the most useful redirections in everyday scripting.
The Basic Syntax
command 2> file
command 2>> file
The number 2 is the file descriptor of standard error. The operator 2> works like >: it opens the file for writing, creates it if it does not exist and empties it if it does. The operator 2>> appends instead. The examples below use a folder that contains one file, real.txt.
ls real.txt missing.txt 2> errors.txt
echo "errors.txt:"
cat errors.txt
Output:
real.txt
errors.txt:
ls: cannot access 'missing.txt': No such file or directory
The listing of the existing file still appeared on the screen, because it went to standard output, which was not redirected. The error message was captured in errors.txt.
No Space Between the Number and the Operator
The digit must touch the >. With a space, Bash treats the 2 as an ordinary argument:
ls missing.txt 2 > oops.txt
echo "status: $?"
Output:
ls: cannot access 'missing.txt': No such file or directory
ls: cannot access '2': No such file or directory
status: 2
ls was asked to list two names, missing.txt and 2, and the output redirection > oops.txt captured only its (empty) standard output. Both error messages stayed on the screen. The correct forms are 2> file and 2>file, with the number directly in front of the operator. A space after the > is fine.
Overwriting and Appending
Like >, a single 2> replaces the file each time. The operator 2>> keeps what is there:
ls gone1 2> errors.txt
ls gone2 2> errors.txt
cat errors.txt
Output:
ls: cannot access 'gone2': No such file or directory
Only the second error remains. Now append:
ls gone3 2>> errors.txt
ls gone4 2>> errors.txt
cat errors.txt
Output:
ls: cannot access 'gone2': No such file or directory
ls: cannot access 'gone3': No such file or directory
ls: cannot access 'gone4': No such file or directory
Appending is the right choice for an error log that should collect problems from many runs:
for f in a b; do ls "$f.txt" 2>> multi.txt; done
cat multi.txt
Output:
ls: cannot access 'a.txt': No such file or directory
ls: cannot access 'b.txt': No such file or directory
Separating Results from Errors
You can combine > and 2> on one command to send each stream to its own file:
ls real.txt missing.txt > good.txt 2> bad.txt
echo "good:"
cat good.txt
echo "bad:"
cat bad.txt
Output:
good:
real.txt
bad:
ls: cannot access 'missing.txt': No such file or directory
The screen stays silent, and each file holds one kind of output. The order of the two redirections does not matter, because they affect different descriptors. This is a handy way to run a long job and review its errors afterward.
Hiding Errors with /dev/null
The special file /dev/null accepts any data and throws it away. Redirecting standard error there hides the messages:
ls real.txt missing.txt 2> /dev/null
echo "status: $?"
Output:
real.txt
status: 2
The error message disappeared, but the exit status is still 2. Hiding a message does not hide the failure, so a script can still check $?.
This technique is common with commands that print many harmless complaints. A search for files across a folder you cannot fully read, for example, produces a permission message for every unreadable folder. Run as an ordinary user:
find /root -name x
find /root -name x 2> /dev/null
Output:
find: '/root': Permission denied
Only the first command printed the message. The second printed nothing, because the message was discarded. Be careful with this habit. Hiding all errors can hide a real problem, such as a mistyped path, so apply 2> /dev/null only to commands where you know the messages are noise.
Checking Whether Any Errors Occurred
When errors go to a file, the file is empty if nothing went wrong. The test -s is true when a file exists and is not empty, so a script can use it to report problems:
ls real.txt 2> clean.txt
ls missing.txt 2> bad2.txt
[ -s clean.txt ] && echo "has errors" || echo "no errors"
[ -s bad2.txt ] && echo "has errors" || echo "no errors"
Output:
no errors
has errors
Note that the file clean.txt was still created, with 0 bytes, because Bash opens the file before the command runs.
Writing Your Own Error Messages
Scripts should send their own error messages to standard error, using >&2. A function is a convenient place to do it:
fail() { echo "error: $*" >&2; return 1; }
fail "bad input" 2> fn.txt
echo "status: $?"
cat fn.txt
Output:
status: 1
error: bad input
The echo inside the function wrote to descriptor 2, so the caller's 2> fn.txt captured it. The message was not on the screen, and the function's return status 1 told the script that it failed. If the caller redirects standard output instead, the message is not captured, and it still shows on the screen:
fail "bad input" > fn2.txt
Output:
error: bad input
The file fn2.txt stayed empty (0 bytes). This is why using the right stream matters: a caller can choose to keep the results and still see the errors, or the other way around.
Errors from the Shell Itself
Some error messages come from Bash, not from the command you wrote. A command that cannot be found is one of them:
nosuchcmd 2> nc.txt
echo "status: $?"
cat nc.txt
Output:
status: 127
bash: nosuchcmd: command not found
Bash looked for the command, failed, and reported the problem on standard error, so 2> nc.txt captured it. The status 127 is the standard code for "command not found". A later lesson on exit codes lists the common values.
There is one case where 2> does not help: when the redirection itself fails. If the target folder does not exist, Bash prints the error for that failure on the screen and does not run the command:
ls missing.txt 2> nodir/e.txt
echo "status: $?"
Output:
bash: nodir/e.txt: No such file or directory
status: 1
Redirecting Errors for a Whole Script or Group
A redirection placed after a group of commands, or after a script call, covers all of them:
{ ls missing.txt; ls nope.txt; } 2> group_err.txt
wc -l < group_err.txt
Output:
2
Both messages were written to the file. The same applies when you run a script:
bash chk.sh 2> chk_err.txt
If chk.sh contains the lines
echo "start"
ls missing.txt
echo "end"
then the screen shows only the normal output while the error goes to the file:
start
end
and chk_err.txt holds:
ls: cannot access 'missing.txt': No such file or directory
Errors and Pipes
A pipe connects standard output only, so 2> on the first command is needed when you want to hide its errors without affecting the pipe:
ls missing.txt real.txt 2> /dev/null | wc -l
ls missing.txt real.txt | wc -l
Output:
1
ls: cannot access 'missing.txt': No such file or directory
1
Both pipelines counted one line, the name real.txt. In the second, the error message still reached the screen, because standard error is not part of the pipe. The words 2> belong to the command they follow, so place it on the command whose errors you want to redirect, not at the end of the pipeline.
Programs That Report Errors Differently
Not every message that looks like an error goes to standard error. Some programs print usage text or warnings on standard output, and some print real errors on standard output, so 2> does not always catch what you expect. When a redirection does not catch a message, test which stream it uses by redirecting each in turn, as in the examples above. The check takes seconds and avoids wrong assumptions in a script.
Where Next
You now know how to move each stream separately. The next lesson shows how to send both streams to the same place, which uses the form 2>&1 and the shortcut &>.