Shell File Descriptors
Contents
Standard File Descriptors
All shells inherit the 0th (STDIN), 1st (STDOUT), and 2nd (STDERR) file descriptors. File descriptors are referenced by their index and an ampersand (&) prefix.
File descriptors can be used with redirection.
The echo builtin normally outputs to STDOUT. To redirect that output to STDERR, try:
echo "Error!" >&2
Note that the STDOUT is redirected implicitly.
Alternatively, to combine the STDOUT and STDERR streams and redirect them to a file, try:
command example >/dev/null 2>&1
Note that the & can be omitted from the source file descriptor.
To read from STDIN, try:
while read line; do : done <&0
Non-standard File Descriptors
Declaration
Non-standard file descriptors have to be opened before they can be accessed.
To open a file descriptor for writing, try:
exec 3> myfifo
Valid indices for file descriptors range from 3 to 9.
To open a file descriptor for reading, try:
exec 3< /path/to/a/temp/file
Mostly only useful for sockets, but a bidirectional file descriptor can be opened like:
exec 3<> /dev/tcp/www.example.com/80
Usage
Non-standard file descriptors, once opened, are used exactly like a standard file descriptor.
To write to one, try:
echo "Debug message" >&3
To read from one, redirect the extra stream into STDIN. For example, to read from &3, try:
while read line; do : done 0<&3
Closing
An opened file descriptor must be closed. This is accomplished by either redirecting it to -, or by redirecting - into it.
exec 3>&- #or: exec 3<&-