4

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.

Thanks.

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.

1 Answer 1

6

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.

1
  • Thanks. My purpose is to figure out unix.stackexchange.com/q/446583/674, by disconnect fd 0, 1 and 2 in bash, before running bash in the same bash shell. Commented May 29, 2018 at 2:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.