0 - stdin (Standard in)
1 - stdout (Standard out)
2 - stderr (Standard error)
Valid file descriptors range from 0 to 19 on most systems and most of the descriptors are not reserved by the system but test the higher ones before use to be sure
You can see where the first three are by running
lsof -a -p $$ -d0,1,2
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
bash 20210 user 0u CHR 136,8 10 /dev/pts/8
bash 20210 user 1u CHR 136,8 10 /dev/pts/8
bash 20210 user 2u CHR 136,8 10 /dev/pts/8
$
You can find out which ones are being used, and for what by typing
ls -l /dev/fd/
$ ls -l /dev/fd/
total 0
lrwx------ 1 user user 64 2009-12-08 17:36 0 -> /dev/pts/8
lrwx------ 1 user user 64 2009-12-08 17:36 1 -> /dev/pts/8
lrwx------ 1 user user 64 2009-12-08 17:36 2 -> /dev/pts/8
lr-x------ 1 user user 64 2009-12-08 17:36 3 -> /proc/20314/fd
$
fd3, process ID 20314 was used to create the display
Suppose you want to redirect stdout to a file. You could use
exec 1> $OUTFILE
Now all output goes to $OUTFILE instead of the terminal. But how to undo that, and redirect stdout back to the terminal?
You first "save" the original stdout file descriptor by associating stdout with another file descriptor, say 4
exec 4<&1 # associate standard output (fd1) with file descriptor 4 exec 1> $OUTFILE # redirect standard output to $OUTFILE
Now, all output goes to $OUTFILE as before and when you want to undo that
exec 1<&4 # restore standard output exec 4>&- # close file descriptor 4
Same thing for stdin
exec 3<&0 # associate standard input (fd0) with file descriptor 3 exec 0 < $INFILE # redirect standard input to $INFILE ... exec 0<&3 # restore standard input exec 3>&- # close file descriptor 3
Same thing for stderr
exec 5<&2 # associate standard error (fd2) with file descriptor 5 exec 2> $ERRFILE # redirect standard error to $ERRFILE ... exec 2<&5 # restore standard error exec 5>&- # close file descriptor 5
![]() |
This site best viewed with a browser |
| Warning: This is a Debian centric site | |
| Many thanks to Debra and Ian Murdock for making Debian possible | |
| First created Apr 22, 2008 ~ Last revised December 09, 2009 |