Is there a way to close all the open file descriptors, without having an explicit list of them beforehand?
Bash – Close all file descriptors in bash
bashfile-descriptorsshell
bashfile-descriptorsshell
Is there a way to close all the open file descriptors, without having an explicit list of them beforehand?
Best Answer
To answer literally, to close all open file descriptors for
bash
:However this really isn't a good idea since it will close the basic file descriptors the shell needs for input and output. If you do this, none of the programs you run will have their output displayed on the terminal (unless they write to the
tty
device directly). If fact in my tests closingstdin
(exec 0>&-
) just causes an interactive shell to exit.What you may actually be looking to do is rather to close all file descriptors that are not part of the shell's basic operation. These are 0 for
stdin
, 1 forstdout
and 2 forstderr
. On top of this some shells also seem to have other file descriptors open by default. Inbash
, for example, you have 255 (also for terminal I/O) and indash
I have 10, which points to/dev/tty
rather than the specifictty
/pts
device the terminal is using. To close everything apart from 0, 1, 2 and 255 inbash
:Note also that
eval
is required when redirecting the file descriptor contained in a variable, if notbash
will expand the variable but consider it part of the command (in this case it would try toexec
the command0
or1
or whichever file descriptor you are trying to close).NOTE: Also using a glob instead of
ls
(eg/proc/$$/fd/*
) seems to open an extra file descriptor for the glob, sols
seems the best solution here.Update
For further information on the portability of
/proc/$$/fd
, please see Portability of file descriptor links. If/proc/$$/fd
is unavailable, then a drop in replacement for the$(ls /proc/$$/fd)
, usinglsof
(if that is available) would be$(lsof -p $$ -Ff | grep f[0-9] | cut -c 2-)
.