简体   繁体   English

Unix管道进入ls

[英]Unix pipe into ls

I thought I understood *nix pipes until now... I have an executable called studio which symlinks to my install of Android Studio and I had assumed I could get the linked-to location with 我以为我理解* nix管道直到现在......我有一个名为studio的可执行文件符号链接到我安装的Android Studio ,我以为我可以获得链接到的位置

which studio | ls -l

But that doesn't work. 但这不起作用。 What it gives me is equivalent to having just run ls -l in the current directory. 它给我的相当于在当前目录中运行ls -l

If I run which studio , I get /home/me/bin/studio . 如果我跑which studio ,我得/home/me/bin/studio And if I run ls -l /home/me/bin/studio I get the expected output showing me the symlink location. 如果我运行ls -l /home/me/bin/studio我会得到预期的输出,显示符号链接位置。

So why doesn't the piped version work? 那么为什么管道版本不起作用呢? What haven't I grokked about pipes? 什么没有我对管道的了解?

To do that you need xargs : 要做到这一点,你需要xargs

which studio | xargs ls -l

From man xargs : 来自man xargs

xargs - build and execute command lines from standard input xargs - 从标准输入构建和执行命令行

To fully understand how pipes work, you can read What is a simple explanation for how pipes work in BASH? 要完全了解管道的工作原理,您可以阅读有关管道如何在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)。

ls does not read its arguments from standard input, but from the command line. ls不会从标准输入中读取其参数,而是从命令行读取。 To get the directory at the command line, you have to use command substitution: 要在命令行中获取目录,必须使用命令替换:

ls -l "$( which studio )"

(The double quotes are needed if the path might contain whitespace.) (如果路径可能包含空格,则需要双引号。)

Since ls -l does not take any input, it does not do anything regarding the output of which studio . 因为ls -l不接受任何输入,所以它对于which studio的输出没有任何作用。 The important thing here is understanding the difference between standard input and arguments. 这里重要的是理解标准输入和参数之间的区别。 The standard input is a special file that is read using the scanf procedure (by a program in C for example), and the arguments to a program are passed to the main procedure as the argv and argc parameters. 标准输入是使用scanf过程(例如,通过C中的程序)读取的特殊文件,程序的参数作为argvargc参数传递给主过程。 argv is an array of null terminated arrays of char, and argc is the length of that array. argv是一个由null终止的char数组的数组, argc是该数组的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM