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.

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在写入时.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...