Web Analytics

Output Redirection

Intermediate~20 min read

Control where output goes using redirection operators. Separate stdout from stderr, append to files, or discard noise.

Stdout and Stderr

Output
Click Run to execute your code
Note: 1> is stdout, 2> is stderr. 2>&1 merges stderr into stdout.
Pro Tip: Send diagnostic messages to stderr: echo "error" 1>&2.
Caution: Overwriting files with > is destructive. Use >> to append.

Common Mistakes

1) Wrong order for 2>&1

# Wrong
cmd 2>&1 > out.txt
# Correct
cmd > out.txt 2>&1

2) Accidental truncation

# Wrong (overwrites)
echo data > file
# Safer append
echo data >> file

Exercise: Split Outputs

Task: Run a command that writes to both stdout and stderr, saving each to separate files. Then produce a combined file with both.

Output
Click Run to execute your code
Show Solution
{ echo out; echo err 1>&2; } 1>out.txt 2>err.txt
{ echo out; echo err 1>&2; } > both.txt 2>&1

Summary

  • Use >/>> for stdout.
  • Use 2> for stderr.
  • Merge with 2>&1; discard via /dev/null.

What's Next?

Chain commands to transform data using Pipes.