How to echo to stderr in Bash
Codemia Knowledge Hub ·
echo writes to stdout (file descriptor 1) by default. To write to stderr (file descriptor 2), redirect its output with >&2. Scripts use this to keep error messages and diagnostics out of normal output, so pipelines process only the intended data while errors are shown or logged separately.
Redirecting echo with >&2
>&2 points file descriptor 1 (stdout) at file descriptor 2 (stderr), so the message goes to stderr. You can confirm it by discarding stdout:
An echoerr helper function
A printf version is more portable, because echo handles escape sequences inconsistently across platforms:
Multi-line messages with cat
Example: separate info and error logs
File descriptors and redirect order
Redirecting stdout and stderr when running a script
Writing to stderr in other languages
Why keep errors off stdout
Pipelines only carry stdout, so errors written to stderr do not pollute the data:
Separate streams let you pipe normal output while still displaying errors, log the two to different files, and suppress errors with 2>/dev/null without losing output.
Redirect mistakes
- Redirect placement:
echo "error" 2> file >&2does not put the message infile. Redirections run left to right, so2> filepoints stderr (empty for echo) at the file, then>&2sends stdout to the original stderr. Put>&2on the echo and redirect stderr where the script is invoked. - Forgetting
>&2in functions: errors written to stdout flow into pipes and corrupt downstream processing. Use>&2for error messages in functions used in pipelines. echo -eportability: some systems interpret escape sequences withecho -e, while others (notably macOS/BSD) print-eliterally. Useprintfinstead.- stderr in command substitution:
result=$(my_command)captures only stdout; stderr still goes to the terminal.result=$(my_command 2>&1)captures stderr too, but mixes both streams into one string. >&2vs2>&1:>&2sends stdout to stderr.2>&1sends stderr to stdout to combine the streams. They do opposite things and are often confused.
Related reading
- Eclipse cannot load SWT libraries
- Eclipse does not highlight matching variables
- Eclipse Error Could not find or load main class
- Eclipse error The import XXX cannot be resolved
- Eclipse hangs at the Android SDK Content Loader
- Eclipse java debugging source not found
- Eclipse returns error message Java was started but returned exit code 1
- Eclipse scala.object cannot be resolved
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseInterview Questions practice on Codemia
Over 11,000 interview practice questions for 300+ companies, searchable by company and role.