Programming
Error Handling
Standard Error
Command Line Tools
Unix/Linux

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

bash
echo "Error: file not found" >&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:

bash
1# Verify: redirect stdout to /dev/null — stderr message still appears
2echo "This goes to stdout"
3echo "This goes to stderr" >&2
4
5# Run: script.sh > /dev/null
6# Output: "This goes to stderr" (stdout is discarded, stderr still shows)

An echoerr helper function

bash
1# Define the function
2echoerr() {
3    echo "$@" >&2
4}
5
6# Usage
7echoerr "Error: invalid argument"
8echoerr "Warning: file is empty"

A printf version is more portable, because echo handles escape sequences inconsistently across platforms:

bash
1echoerr() {
2    printf '%s\n' "$@" >&2
3}
4
5echoerr "Error: connection refused"

Multi-line messages with cat

bash
1# Here-doc to stderr
2cat >&2 <<EOF
3Error: configuration file is missing.
4Expected location: /etc/myapp/config.yaml
5Run 'myapp --init' to create a default configuration.
6EOF

Example: separate info and error logs

bash
1#!/bin/bash
2
3log_error() {
4    echo "[ERROR] $1" >&2
5}
6
7log_info() {
8    echo "[INFO] $1"
9}
10
11process_file() {
12    local file="$1"
13
14    if [ ! -f "$file" ]; then
15        log_error "File not found: $file"
16        return 1
17    fi
18
19    log_info "Processing $file"
20    # ... process the file ...
21    log_info "Done processing $file"
22}
23
24process_file "$1"
bash
1# Run the script — stdout and stderr go to different places
2./script.sh myfile.txt > output.log 2> error.log
3
4# output.log contains: [INFO] messages
5# error.log contains: [ERROR] messages

File descriptors and redirect order

bash
1# File descriptor 0 = stdin  (input)
2# File descriptor 1 = stdout (normal output)
3# File descriptor 2 = stderr (error output)
4
5# Redirect stdout to a file
6echo "normal" > output.txt
7
8# Redirect stderr to a file
9echo "error" 2> error.txt    # Wrong: this redirects stderr of echo, not the output
10echo "error" >&2 2> error.txt # Wrong: order matters
11
12# Correct: redirect the echo's stderr output
13echo "error" >&2              # Writes to stderr
14# Then capture stderr at the caller level:
15./script.sh 2> error.txt

Redirecting stdout and stderr when running a script

bash
1# Redirect stdout and stderr to different files
2./script.sh > output.log 2> error.log
3
4# Redirect both to the same file
5./script.sh > all.log 2>&1
6
7# Bash shorthand (4.0+)
8./script.sh &> all.log
9
10# Pipe only stderr (swap descriptors)
11./script.sh 3>&1 1>&2 2>&3 | grep "ERROR"

Writing to stderr in other languages

python
1# Python
2import sys
3print("Error message", file=sys.stderr)
4
5# Or
6sys.stderr.write("Error message\n")
javascript
1// Node.js
2console.error("Error message");  // Writes to stderr
3console.log("Normal output");    // Writes to stdout
4
5// Explicit
6process.stderr.write("Error message\n");
go
// Go
fmt.Fprintln(os.Stderr, "Error message")
c
// C
fprintf(stderr, "Error message\n");

Why keep errors off stdout

Pipelines only carry stdout, so errors written to stderr do not pollute the data:

bash
1# Pipeline only processes stdout — stderr passes through to terminal
2find / -name "*.conf" 2>/dev/null | grep "nginx"
3# Permission denied errors go to /dev/null
4# Found files pass through the pipe to grep
5
6# Without stderr redirection, errors pollute the pipeline
7find / -name "*.conf" | grep "nginx"
8# "Permission denied" lines mix with results

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 >&2 does not put the message in file. Redirections run left to right, so 2> file points stderr (empty for echo) at the file, then >&2 sends stdout to the original stderr. Put >&2 on the echo and redirect stderr where the script is invoked.
  • Forgetting >&2 in functions: errors written to stdout flow into pipes and corrupt downstream processing. Use >&2 for error messages in functions used in pipelines.
  • echo -e portability: some systems interpret escape sequences with echo -e, while others (notably macOS/BSD) print -e literally. Use printf instead.
  • 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.
  • >&2 vs 2>&1: >&2 sends stdout to stderr. 2>&1 sends stderr to stdout to combine the streams. They do opposite things and are often confused.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Interview Questions practice on Codemia

Over 11,000 interview practice questions for 300+ companies, searchable by company and role.

Browse interview questions