🎓 A1Learner
🔍
0 of 45 lessons completed

Bash File Descriptor Duplication

File descriptor duplication is the act of pointing one descriptor at the same open stream as another. Duplicated descriptors share one stream, so saving and restoring a stream becomes a two-step copy.

Save and restore standard output

Descriptor 3 saves standard output before output moves to a file. Restoring from descriptor 3 brings the screen back.

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

Merge error output into a file

The redirect 2>&1 follows the file redirect, so both streams land in one file. The file shows the output line first and the error line second.

bash -c 'echo "out line"; echo "err line" >&2' > merged.txt 2>&1
cat merged.txt

Duplicated input shares one position

Descriptor 4 duplicates descriptor 3, so both read from one shared position. The first read takes line one, and the second read takes line two.

printf 'first line\nsecond line\n' > data.txt
exec 3<data.txt
exec 4<&3
read -r -u 3 a
read -r -u 4 b
exec 3<&-
exec 4<&-
echo "fd3 read: $a"
echo "fd4 read: $b"

Example

exec 3>&1
exec 4>&2
exec > quiet.txt 2> errors.txt
echo "quiet line"
ls missing-file.txt
exec 1>&3
exec 2>&4
exec 3>&-
exec 4>&-
echo "screen again"
echo "quiet file:"
cat quiet.txt
echo "error file:"
cat errors.txt

Key points

  • Copy syntax: >& copies an output descriptor, and <& copies an input descriptor.
  • Save first: exec 3>&1 saves standard output before any redirect changes it.
  • Restore after: exec 1>&3 puts standard output back, then exec 3>&- closes the spare copy.
  • Shared offset: duplicated input descriptors share one read position, so a read through either one moves both.
  • Merge errors: 2>&1 sends error output to the same stream as standard output.
  • Order matters: 2>&1 must come after the output redirect it should follow.
  • Close copies: a spare copy left open can keep a pipe or file open longer than planned.
  • Forward note: exec redirection is taught in full in Bash Exec Redirection, the next lesson.

In this example, the script saves standard output on descriptor 3 and standard error on descriptor 4. It then sends output to a quiet file and errors to an error file. A normal line lands in the quiet file, and a failed listing lands in the error file. Both streams are restored before the screen line and the two files print.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In `cmd > out.txt 2>&1`, why must 2>&1 come after > out.txt?