使用 bash 命令(带管道)的输出作为另一个命令的参数 [英] Use output of bash command (with pipe) as a parameter for another command
问题描述
我正在寻找一种方法来使用命令(比如 command1)的输出作为另一个命令(比如 command2)的参数.
I'm looking for a way to use the ouput of a command (say command1) as an argument for another command (say command2).
我在尝试 grep
who
命令的输出但使用另一组命令(实际上是 tty
)给出的模式时遇到了这个问题通过管道传输到 sed
).
I encountered this problem when trying to grep
the output of who
command but using a pattern given by another set of command (actually tty
piped to sed
).
如果 tty
显示:
/dev/pts/5
和who
显示:
root pts/4 2012-01-15 16:01 (xxxx)
root pts/5 2012-02-25 10:02 (yyyy)
root pts/2 2012-03-09 12:03 (zzzz)
目标:
我只想要有关pts/5"的行所以我通过管道将 tty
传送到 sed
如下:
$ tty | sed 's//dev///'
pts/5
测试:
尝试的以下命令不起作用:
Test:
The attempted following command doesn't work:
$ who | grep $(echo $(tty) | sed 's//dev///')"
可能的解决方案:
我发现以下方法可以正常工作:
Possible solution:
I've found out that the following works just fine:
$ eval "who | grep $(echo $(tty) | sed 's//dev///')"
但我确信可以避免使用 eval
.
作为最后一个边节点:我注意到 who
的-m"参数给了我我想要的东西(只得到 who
code> 链接到当前用户).但是我仍然很好奇如何使管道和命令嵌套的这种组合起作用......
As a final side node: I've noticed that the "-m" argument to who
gives me exactly what I want (get only the line of who
that is linked to current user). But I'm still curious on how I could make this combination of pipes and command nesting to work...
推荐答案
在 Bash 变量修改,尽管@ruakh 指出这在单行版本中不起作用(没有分号分隔命令).我将保留第一种方法,因为我认为它不能在一行中工作很有趣:
You can do this without resorting to sed with the help of Bash variable mangling, although as @ruakh points out this won't work in the single line version (without the semicolon separating the commands). I'm leaving this first approach up because I think it's interesting that it doesn't work in a single line:
TTY=$(tty); who | grep "${TTY#/dev/}"
这首先将 tty
的输出放入一个变量中,然后在 grep 使用它时擦除前导 /dev/
.但是没有分号 TTY
在 bash 为 grep 进行变量扩展/修改时不在环境中.
This first puts the output of tty
into a variable, then erases the leading /dev/
on grep's use of it. But without the semicolon TTY
is not in the environment by the moment bash does the variable expansion/mangling for grep.
这是一个有效的版本,因为它生成了一个具有已修改环境(具有 TTY
)的子 shell:
Here's a version that does work because it spawns a subshell with the already modified environment (that has TTY
):
TTY=$(tty) WHOLINE=$(who | grep "${TTY#/dev/}")
结果留在$WHOLINE
中.
这篇关于使用 bash 命令(带管道)的输出作为另一个命令的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!