简体   繁体   中英

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 file to 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?

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.

In general, cat prints the contents of a file or from the stdin. If you don't provide a file and redirect the stdin to a file, then cat doesn't have any input to read from.

The correct form would be: cat <&0 > file.txt , that is:

  • <&0 redirect stdin as input for cat (similar to cat < some-file.txt )
  • > file.txt redirect the output of cat to file.txt

This works both for:

  • echo "hello" | cat <&0 > file.txt echo "hello" | cat <&0 > file.txt , that is, piping the output of some command
  • cat <&0 > file.txt as stand alone and you type directly on the console (quit with Ctrl-C)

As a side note:

# This works (no errors) as cat has a file in input, but:
# 1. the contents of some-file-with-contents.txt will be printed out
# 2. file.txt will not contain anything
cat some-file-with-contents.txt 0>file.txt

# This works (no errors) as cat has a file in input, but:
# 1. the contents of some-file-with-contents.txt will be printed out
# 2. file.txt will not contain anything
# 3. copy.txt will have the contents of some-file-with-contents.txt
cat some-file-with-contents.txt 0>file.txt 1>copy.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM