In bash we can create a connection between a file descriptor and a file, e.g. by

exec > /path/to/myfile

which connects fd 1 to the file.

I was wondering how we can disconnect a fd from any file connected to it, so that the fd isn't connected to any file? Note that /dev/null and /dev/tty are files.


My purpose is to figure out Does a shell automatically connect file descriptors 0, 1 and 2 to its controlling terminal?, by disconnect fd 0, 1 and 2 in bash, before running bash in the same bash shell.


What you want is close the file descriptor which in Bourne-like shell is done with the >&- (defaults to fd 1) or <&- (defaults to fd 0) operator:

exec >&-
exec 1>&-
exec 1<&-

are all equivalent and result in a close(1) system call being made.

Note that it's generally a bad idea to close file descriptors 0, 1 and 2, as most commands expect those to be open (it's their stdin, stdout and stderr), and them opening a file could cause that file to inadvertently become their stdin/stdout/stderr and what they print on stdout or stderr could end up being written in those files.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.