[英]Pipe printf to ls in Bash?
So I'm learning about pipes in bash and I found this pithy description: 所以我正在学习bash中的管道,我发现这个简洁的描述:
A Unix pipe connects the STDOUT (standard output) file descriptor of the first process to the STDIN (standard input) of the second.
Unix管道将第一个进程的STDOUT(标准输出)文件描述符连接到第二个进程的STDIN(标准输入)。 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.
然后会发生的是,当第一个进程写入其STDOUT时,第二个进程可以立即读取该输出(来自STDIN)。
Given this understanding, let's connect the STDOUT of printf
to the STDIN of ls
. 鉴于这种理解,让我们将
printf
的STDOUT连接到ls
的STDIN。 For simplicity, print the parent directory ( printf ..
). 为简单起见,打印父目录(
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$
I want to be doing: ls ..
but it seems that all I'm getting is ls
. 我想做:
ls ..
但似乎我得到的只是ls
。 Why is this so? 为什么会这样? How can I
ls
the parent directory using pipes? 我怎样才能
ls
使用管道的父目录? Am I misunderstanding pipes? 我误解管道吗?
Many programs don't read from stdin
, not just ls
. 许多程序不读取
stdin
,而不仅仅是ls
。 It is also possible that a program might not write to stdout
either. 程序也可能无法写入
stdout
。
Here is a little experiment that might clarify things. 这是一个可以澄清事情的小实验。 Carry out these steps:
执行以下步骤:
cat > file1
This is file1
^D
The ^D is you pressing <CTRL>+D
, which is the default end-of-file. ^ D是您按
<CTRL>+D
,这是默认的文件结尾。 So, first we are calling the cat
program and redirecting its stdout
to file1
. 所以,首先我们调用
cat
程序并将其stdout
重定向到file1
。 If you don't supply an input filename then it reads from stdin
, so we type "This is file1". 如果你没有提供输入文件名,那么它从
stdin
读取,所以我们输入“This is file1”。
Now do similar: 现在做类似的:
cat > file2
This is file2
^D
Now if you: 现在,如果你:
cat < file1
You get: 你得到:
This is file1
what if you: 如果你:
cat file1 | cat file2
or: 要么:
cat file2 < file1
Why? 为什么? Because if you supply an input filename then the
cat
program does not read stdin
, just like ls
. 因为如果你提供一个输入文件名,那么
cat
程序就不会读取stdin
,就像ls
一样。
Now, how about: 现在,怎么样:
cat - file1 < file2
By convention the -
means a standard stream, stdin
when reading or stdout
when writing. 按照惯例,
-
表示标准流, stdin
在读取时或stdout
在写入时。
The problem is ls
does not read from stdin
as you intended it to do. 问题是
ls
没有像你想要的那样从stdin
读取。 You need to use a tool that reads from the stdin
like xargs
and feed the read input to ls
您需要使用一个从
stdin
读取的工具,如xargs
,并将读取输入提供给ls
printf "someSampleFolderOrFile" | xargs ls
xargs man
page, xargs man
页,
xargs - build and execute command lines from standard input
xargs - 从标准输入构建和执行命令行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.