Lately I found a nice article giving some deeper insight about shell in- and output redirection for bash. The most common used form is like PROGRAM >FILE.OUT
which redirects the standard output of PROGRAM
to FILE.OUT
. One lesser know but nevertheless neat feature is about closing file descriptors. It is actually not covered by the documentation, so here is the syntax for it: [N]>&-
. This will close the file descriptor N
or stdout when N
is omitted. It’s a pretty nice feature when you’ve opened additional files within a shell script via ‘exec N>FILE
‘ and want to close those file descriptors. But beside that, it can also be used to start a program with some or all of its default file descriptors closed.
Take a look at those two calls to ls
:
minipli@zaphod:~$ ls -g /proc/self/fd
total 0
lrwx------ 1 minipli 64 May 14 21:43 0 -> /dev/pts/0
lrwx------ 1 minipli 64 May 14 21:43 1 -> /dev/pts/0
lrwx------ 1 minipli 64 May 14 21:43 2 -> /dev/pts/0
lr-x------ 1 minipli 64 May 14 21:43 3 -> /proc/13868/fd
minipli@zaphod:~$
minipli@zaphod:~$ ls -g /proc/self/fd 0>&- 2>&-
total 0
lr-x------ 1 minipli 64 May 14 21:43 0 -> /proc/13869/fd
lrwx------ 1 minipli 64 May 14 21:43 1 -> /dev/pts/0
The first listing shows us file descriptors 0, 1 and 2 connected to the terminal; fd 3 is opened by ls
for reading the directory content itself. In the second listing stdin and stderr were closed prior starting the ls
program so the fd for the directory ends up as 0 — which is normaly used for stdin. With that in mind, you have a tool at hand, right within your shell, that gives you the ability to test how programs behave with there standard file descriptors closed. For example, you can try something like buggy_programm 0>&- 1>&- 2>&-
or variations of it with just stdin or stdout closed and see how it breaks. A good starter may be: ls /proc/self/fd 1>&-