Skip to content
Advertisement

Why cat 0>file doesn’t work

In Unix, I know that 0 1 and 2 represent stdin stdout and stderr.

As my understanding, the command cat meaning “concatenate” can concatenate different files.

For example, cat file>&1 can concatenate the file and the stdout and the arrow means the redirection from the fileto the stdout, so we can see the content of the file from the terminal which is stdout.

But, I don’t understand why the command below doesn’t work:
cat 0>file

I think this command should work, because it means that to concatenate the stdin and the file and do the redirection from the stdin to the file.
However it doesn’t work and I get an error:

cat: input error on standard input: Bad file number

I thought that cat > file and cat 0>file are exactly the same, just like cat file and cat file>&1 are exactly the same, but it seems I’m wrong…

To my surprise, cat 1>file and cat > file are the same. Why?

Advertisement

Answer

Syntax 0>file redirects stdin into a file (if that makes sense). Then cat tries to read from stdin and gets EBADF error because stdin is no longer an input stream.

EBADF – fd is not a valid file descriptor or is not open for reading.

Note that redirections (< and >) are handled by the shell, cat does not see 0>file bit.

Advertisement