Skip to main content

What does `exec {STDIN}>&0` do? [Resolved]

1 Answers

From man bash:


Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. [...]

Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than or equal to 10 and assign it to varname. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close.

So the lines in your example:

exec {STDIN}>&0
exec {STDOUT}>&1
exec {STDERR}>&2

have the effect of assigning three new file descriptors that are duplicates of the current descriptors 0, 1 and 2, and assigning the values of those new descriptors to the shell variables $STDIN, $STDOUT and $STDERR respectively. After those commands have been executed you should be able to see the values of the duplicate descriptors:

10 11 12

The most likely reason for doing this is to save the current disposition of stdin, stdout and stderr so that the script can freely redirect descriptors 0, 1 and 2 to various places as needed by some parts of the script, and then restore them to their original targets by doing something like:

exec 0>&$STDIN
exec 1>&$STDOUT
exec 2>&$STDERR

credit: ottomeister
Answered June 24, 2019
Your Answer