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

linux – 在Bash中管道打印到ls?,第1张

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

Source

鉴于这种理解,让我们将printf的STDOUT连接到ls的STDIN.为简单起见,打印父目录(printf ..).

~/Desktop/pipes$mkdir sub~/Desktop/pipes$lssub~/Desktop/pipes$cd sub(no files)~/Desktop/pipes/sub$printf .. | ls(no files)~/Desktop/pipes/sub$

我想做:ls ..但似乎我得到的只是ls.为什么会这样?我如何使用管道使用父目录?我误解管道吗?

@H_419_29@解决方法 许多程序不读取stdin,而不仅仅是ls.程序也可能无法写入stdout.

这是一个可以澄清事情的小实验.执行以下步骤:

cat > file1This is file1^D

^ D是你按< CTRL> D,这是默认的文件结尾.所以,首先我们调用cat程序并将其stdout重定向到file1.如果你没有提供输入文件名,那么它从stdin读取,所以我们输入“This is file1”.

现在做类似的:

cat > file2This is file2^D

现在,如果你:

cat < file1

你得到:

This is file1

如果你:

cat file1 | cat file2

要么:

cat file2 < file1

为什么?因为如果你提供一个输入文件名,那么cat程序就不会读取stdin,就像ls一样.

现在,怎么样:

cat - file1 < file2

按照惯例,– 表示标准流,stdin在读取时或stdout在写入时.

总结

以上是内存溢出为你收集整理的linux – 在Bash中管道打印到ls?全部内容,希望文章能够帮你解决linux – 在Bash中管道打印到ls?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1024450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存