Use output of bash command (with pipe) as a parameter for another command

前端 未结 4 1404
Happy的楠姐
Happy的楠姐 2020-12-06 02:17

I\'m looking for a way to use the ouput of a command (say command1) as an argument for another command (say command2).

I encountered this problem when trying to

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 02:43

    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/}"
    

    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.

    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/}")
    

    The result is left in $WHOLINE.

提交回复
热议问题