🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Advanced Redirection

Advanced redirection controls where each numbered stream goes. Stream 1 is standard output, and stream 2 is standard error.

2>&1 after >file sends both streams to one file

Both lines land in the same file. The error line follows the output line because both share one destination.

{
echo "standard out"
echo "standard err" >&2
} > both.txt 2>&1
cat both.txt

2>&1 before >file splits the streams

The error line goes to the outer file, and the output line goes to the inner file. The order of the two redirections decides which stream each file gets.

{
  {
    echo "standard out"
    echo "standard err" >&2
  } 2>&1 > before.txt
} > outer.txt
echo "before file:"
cat before.txt
echo "outer file:"
cat outer.txt

exec saves and restores standard output

Descriptor 3 holds a copy of the screen output. The middle line goes to the file, and the last line returns to the screen.

exec 3>&1
exec > saved.txt
echo "hidden line"
exec 1>&3 3>&-
echo "back on screen"
cat saved.txt

Example

{
echo "report title"
echo "report line one"
echo "report line two"
} > report.txt
cat report.txt

Key points

  • File descriptor: a number that names an open stream, such as 1 for output and 2 for errors.
  • 2>&1: a redirection that sends stream 2 to the place stream 1 currently goes.
  • Order matters: redirections are read from left to right, so the same symbols can give different results.
  • exec 3>&1: a way to save a copy of standard output in descriptor 3.
  • exec 1>&3: a way to restore standard output from the saved copy in descriptor 3.
  • Block redirection: putting { } > file around commands sends the whole block's output to that file.

In this example, the braces group three echo commands into one block. The > report.txt after the closing brace sends the whole block's output to the file. The cat command then prints the file, which holds all three lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does cmd > file 2>&1 do?