File Descriptors in Shell

Level 5163 keystrokes

exec without a command changes the shell's own file descriptors: stdout is saved in fd 3, stdout and stderr are sent to log files, then stdout is restored and fd 3 is closed. Afterwards the two log files are shown on the terminal.

Shell code

# Copy the current stdout (fd 1) to fd 3 to restore it later
1exec 3>&1
# From now on stdout goes to output.log and stderr to error.log
2exec 1>output.log 2>error.log
# Written to output.log, not the terminal
3echo "This goes to output.log"
# >&2 sends this line to stderr, i.e. error.log
4echo "Error message" >&2
# Restore stdout from fd 3, then close fd 3 with 3>&-
5exec 1>&3 3>&-
# This appears on the terminal again (stderr still goes to error.log)
6echo "Back to terminal"
# Show what was captured in each file
7cat output.log
8cat error.log

Output

Back to terminal
This goes to output.log
Error message
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 6
  • >× 6
  • .× 5
  • &× 4
  • -× 1

More Shell examples at level 5

← Shell typing practice