微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 在Bash中管道打印到ls?

所以我正在学习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.

@L_404_0@

鉴于这种理解,让我们将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在写入时.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐