使用bash命令(管)的输出作为另一个命令的参数 [英] Use output of bash command (with pipe) as a parameter for another command
问题描述
我正在寻找一种方式来使用命令的输出中(比如命令1)作为另一个命令的参数(比如命令2)。
I'm looking for a way to use the ouput of a command (say command1) as an argument for another command (say command2).
我试图的grep
时的输出遇到了这个问题谁
命令,但使用由另一组给出一个模式命令(实际上的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
和谁
显示:
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)
目标:
我只想就行了(S)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\///')"
但我敢肯定使用评估
的可以避免的。
But I'm sure the use of eval
could be avoided.
的作为最后一面节点:我已经注意到,-m参数谁
给我正是我想要的(只得到线谁
链接到当前用户)。但我仍然好奇,我如何可以使管道的组合,并命令筑巢工作... 的
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...
推荐答案
您可以做到这一点,而不诉诸使用的猛砸变量识别码,虽然身为@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
的输出到一个变量,然后擦除领先的/ dev /
上的grep的使用它。但是,如果没有分号 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.
下面是一条什么工作的一个版本,因为它产生与已经修改后的环境子shell(即具有 TTY
)
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屋!