所以我正在学习bash中的管道,我发现这个简洁的描述:
A Unix pipe connects the STDOUT (standard output) file descriptor of
the first process to the STDIN (standard input) of the second. What
happens then is that when the first process writes to its STDOUT, that
output can be immediately read (from STDIN) by the second process.
鉴于这种理解,让我们将printf的STDOUT连接到ls的STDIN.为简单起见,打印父目录(printf ..).
~/Desktop/pipes$mkdir sub
~/Desktop/pipes$ls
sub
~/Desktop/pipes$cd sub
(no files)
~/Desktop/pipes/sub$printf .. | ls
(no files)
~/Desktop/pipes/sub$
我想做:ls ..但似乎我得到的只是ls.为什么会这样?我如何使用管道使用父目录?我误解管道吗?
解决方法:
许多程序不读取stdin,而不仅仅是ls.程序也可能无法写入stdout.
这是一个可以澄清事情的小实验.执行以下步骤:
cat > file1
This is file1
^D
^ D是你按< CTRL> D,这是默认的文件结尾.所以,首先我们调用cat程序并将其stdout重定向到file1.如果你没有提供输入文件名,那么它从stdin读取,所以我们输入“This is file1”.
现在做类似的:
cat > file2
This is file2
^D
现在,如果你:
cat < file1
你得到:
This is file1
如果你:
cat file1 | cat file2
要么:
cat file2 < file1
为什么?因为如果你提供一个输入文件名,那么cat程序就不会读取stdin,就像ls一样.
现在,怎么样:
cat - file1 < file2
按照惯例, – 表示标准流,stdin在读取时或stdout在写入时.