Why can’t I do ls -a 1>&-

file-descriptorsioio-redirection

Why can't we just close stdout for a process?

I was trying out redirection commands. The following works:

ls -a 0>&-
ls -a 2>&-

which means close stdin and stderr for the process ls -a. But why does closing stdout fail? I am getting

aniket@aniket-Compaq-610:~/Downloads$ ls -a 1>&-
ls: write error: Bad file descriptor

I know it does not make sense to close stdout here but I am wondering why it is not allowed?

Best Answer

Obviously closing stdout does not fail, on the contrary, it succeeds because writing on it fails, as can be seen from the error message. Edit: to clarify my answer, what happens is that you first tell the shell to close the file descriptor, then the ls program tries to write to it. This is where the error message comes from.

Related Question