在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 > file
和cat 0>file
完全相同,就像cat file
和cat file>&1
完全相同,但似乎我错了...
令我惊讶的是,cat 1>file
和cat > file
相同。为什么?
语法0>file
将stdin
重定向到文件(如果有道理)。然后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.txt
将cat
的输出重定向到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