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

前端 未结 4 1419
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:46

    @Eduardo's answer is correct (and as I was writing this, a couple of other good answers have appeared), but I'd like to explain why the original command is failing. As usual, set -x is very useful to see what's actually happening:

    $ set -x
    $ who | grep $(echo $(tty) | sed 's/\/dev\///')
    + who
    ++ sed 's/\/dev\///'
    +++ tty
    ++ echo not a tty
    + grep not a tty
    grep: a: No such file or directory
    grep: tty: No such file or directory
    

    It's not completely explicit in the above, but what's happening is that tty is outputting "not a tty". This is because it's part of the pipeline being fed the output of who, so its stdin is indeed not a tty. This is the real reason everyone else's answers work: they get tty out of the pipeline, so it can see your actual terminal.

    BTW, your proposed command is basically correct (except for the pipeline issue), but unnecessarily complex. Don't use echo $(tty), it's essentially the same as just tty.

提交回复
热议问题