为什么 cat 0>file 不起作用

Why cat 0>file doesn't work

在 Unix 中,我知道 0 1 和 2 代表 stdin stdout 和 stderr。

据我了解,命令cat意思是"concatenate"可以连接不同的文件。

例如cat file>&1可以连接file和stdout,箭头表示从file重定向到stdout,所以我们可以看到[的内容=12=] 来自标准输出的终端。

但是,我不明白为什么下面的命令不起作用:
cat 0>file

我认为这个命令应该有效,因为它意味着连接标准输入和 file 并从标准输入重定向到 file
但是它不起作用,我得到一个错误:

cat: input error on standard input: Bad file number

我以为cat > filecat 0>file是一模一样的,就像cat filecat file>&1是一模一样的,但是看来我错了。 ..

令我惊讶的是,cat 1>filecat > file 是一样的。为什么?

语法 0>filestdin 重定向到一个文件(如果这有意义的话)。然后 cat 尝试从 stdin 读取并得到 EBADF 错误,因为 stdin 不再是输入流。

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

请注意,重定向(< 和 >)由 shell 处理,cat 看不到 0>file 位。

一般来说,cat 打印文件或标准输入的内容。如果您不提供文件并将标准输入重定向到文件,则 cat 没有任何输入可供读取。

正确的形式是:cat <&0 > file.txt,即:

  • <&0 将标准输入重定向为 cat 的输入(类似于 cat < some-file.txt
  • > file.txtcat 的输出重定向到 file.txt

这适用于:

  • echo "hello" | cat <&0 > file.txt,即管道化一些命令的输出
  • cat <&0 > file.txt 作为独立的,您可以直接在控制台上键入(使用 Ctrl-d 退出)

旁注:

# 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