为什么 cat 0>file 不起作用



在unix中,我知道0 1和2表示stdin stdout和stderr。

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

例如, cat file>&1可以将file和stdout和箭头串联,而箭头是指从file重定向到Stdout,因此我们可以从terminal中看到file的内容。



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

我认为此命令应该起作用,因为这意味着将stdin和 file加入并从stdin重定向到 file
但是它不起作用,我会遇到错误:

CAT:标准输入上的输入错误:不良文件编号

我认为cat > filecat 0>file完全相同,就像cat filecat file>&1完全相同,但似乎我错了...

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

语法0>filestdin重定向到文件(如果有道理)。然后cat试图从stdin读取并获取EBADF错误,因为stdin不再是输入流。

EBADF -fd不是有效的文件描述符或不打开读数。

请注意,重定向(< and>)由外壳处理,CAT看不到0>file位。

通常, cat打印文件的内容或stdin。如果您不提供文件并将stdin重定向到文件,则cat没有任何输入可读取。

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

  • <&0重定向stdin作为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

最新更新