How do file descriptors work?

Trcx picture Trcx · Aug 16, 2011 · Viewed 70.5k times · Source

Can someone tell me why this does not work? I'm playing around with file descriptors, but feel a little lost.

#!/bin/bash
echo "This"
echo "is" >&2
echo "a" >&3
echo "test." >&4

The first three lines run fine, but the last two error out. Why?

Answer

dogbane picture dogbane · Aug 16, 2011

File descriptors 0, 1 and 2 are for stdin, stdout and stderr respectively.

File descriptors 3, 4, .. 9 are for additional files. In order to use them, you need to open them first. For example:

exec 3<> /tmp/foo  #open fd 3.
echo "test" >&3
exec 3>&- #close fd 3.

For more information take a look at Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.