加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 00:43:38 所属栏目:Linux 来源:网络整理
导读:所以我正在学习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 t
所以我正在学习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$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在写入时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读