0
0
Linux CLIscripting~5 mins

stderr redirection (2>, 2>>) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes when you run commands, errors appear on the screen mixed with normal messages. Stderr redirection lets you save or hide these error messages separately so your screen stays clean or you can check errors later.
When you want to save error messages from a command to a file for later review.
When you want to hide error messages so they don't clutter your terminal output.
When you want to add new error messages to an existing error log without overwriting it.
When you want to separate normal output and error messages into different files.
When debugging scripts and you want to capture only the errors.
Commands
This command tries to list a folder that does not exist. The error message is saved to the file error.log instead of showing on the screen.
Terminal
ls /nonexistent 2> error.log
Expected OutputExpected
No output (command runs silently)
This command shows the content of error.log to see the saved error message from the previous command.
Terminal
cat error.log
Expected OutputExpected
ls: cannot access '/nonexistent': No such file or directory
This command tries to list another non-existing folder. The error message is added to the end of error.log without deleting previous errors.
Terminal
ls /anotherfake 2>> error.log
Expected OutputExpected
No output (command runs silently)
This command shows the updated error.log file with both error messages saved.
Terminal
cat error.log
Expected OutputExpected
ls: cannot access '/nonexistent': No such file or directory ls: cannot access '/anotherfake': No such file or directory
Key Concept

If you remember nothing else from this pattern, remember: 2> overwrites error output to a file, while 2>> appends errors to the file.

Common Mistakes
Using > instead of 2> to redirect errors
The > symbol redirects normal output (stdout), not errors (stderr), so error messages still show on screen.
Use 2> to redirect error messages specifically.
Using 2> when wanting to add errors to an existing file
2> overwrites the file, deleting previous error messages.
Use 2>> to append errors without deleting existing content.
Summary
Use 2> to redirect error messages to a file, replacing its content.
Use 2>> to append error messages to the end of a file.
Check saved error messages by viewing the file with commands like cat.