Linux 命令:为什么重定向运算符 - |即管道在这里失败?
Linux Command : Why does the redirection operator - | i.e. piping fail here?
我正在学习 Shell (Bash) 脚本的初级读物,我有以下疑问:
Why does not the following command print the contents of cp's
directory : which cp | ls -l
Does not piping by definition mean that we pass the output of one command to another i.e. redirect the output ?
有人可以帮助我吗?我是新手..
会是,
$ ls -l $(which cp)
-rwxr-xr-x 1 root root 130304 Mar 24 2014 /bin/cp
或
$ which cp | xargs ls -l
-rwxr-xr-x 1 root root 130304 Mar 24 2014 /bin/cp
要将一个命令的输出作为另一个命令的参数传递,您需要使用 xargs
和管道符号。
来自man xargs
xargs - build and execute command lines from standard input.xargs reads items
from the standard input, delimited by blanks (which can be protected
with double or single quotes or a backslash) or newlines, and executes
the command (default is /bin/echo) one or more times with any initial-
arguments followed by items read from standard input. Blank lines on
the standard input are ignored.
which
的输出正在通过管道传输到 ls
的标准输入。但是,ls
不接受任何标准输入。您希望它(我想)作为参数传递。有几种方法可以做到这一点:
which cp | xargs ls -l
或
ls -l `which cp`
或
ls -l $(which cp)
在第一个示例中,xargs
命令采用前一个命令的标准输出,并将每一行作为名称紧跟在 xargs
之后的命令的参数。所以,例如
find / | xargs ls -l
将对文件系统中的每个文件执行 ls -l
(对于特殊命名的文件存在一些问题,但这超出了本答案的范围)。
其余两个大致相同,使用 shell 来执行此操作,将 which
的输出扩展到 cp
.
的命令行
我正在学习 Shell (Bash) 脚本的初级读物,我有以下疑问:
Why does not the following command print the contents of
cp's
directory :which cp | ls -l
Does not piping by definition mean that we pass the output of one command to another i.e. redirect the output ?
有人可以帮助我吗?我是新手..
会是,
$ ls -l $(which cp)
-rwxr-xr-x 1 root root 130304 Mar 24 2014 /bin/cp
或
$ which cp | xargs ls -l
-rwxr-xr-x 1 root root 130304 Mar 24 2014 /bin/cp
要将一个命令的输出作为另一个命令的参数传递,您需要使用 xargs
和管道符号。
来自man xargs
xargs - build and execute command lines from standard input.xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial- arguments followed by items read from standard input. Blank lines on the standard input are ignored.
which
的输出正在通过管道传输到 ls
的标准输入。但是,ls
不接受任何标准输入。您希望它(我想)作为参数传递。有几种方法可以做到这一点:
which cp | xargs ls -l
或
ls -l `which cp`
或
ls -l $(which cp)
在第一个示例中,xargs
命令采用前一个命令的标准输出,并将每一行作为名称紧跟在 xargs
之后的命令的参数。所以,例如
find / | xargs ls -l
将对文件系统中的每个文件执行 ls -l
(对于特殊命名的文件存在一些问题,但这超出了本答案的范围)。
其余两个大致相同,使用 shell 来执行此操作,将 which
的输出扩展到 cp
.