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

前端 未结 4 1415
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:45

    One usually uses xargs to make the output of one command an option to another command. For example:

    $ cat command1
    #!/bin/sh
    
    echo "one"
    echo "two"
    echo "three"
    
    $ cat command2
    #!/bin/sh
    
    printf '1 = %s\n' "$1"
    
    $ ./command1 | xargs -n 1 ./command2
    1 = one
    1 = two
    1 = three
    $ 
    

    But ... while that was your question, it's not what you really want to know.

    If you don't mind storing your tty in a variable, you can use bash variable mangling to do your substitution:

    $ tty=`tty`; who | grep -w "${tty#/dev/}"
    ghoti            pts/198  Mar  8 17:01 (:0.0)
    

    (You want the -w because if you're on pts/6 you shouldn't see pts/60's logins.)

    You're limited to doing this in a variable, because if you try to put the tty command into a pipe, it thinks that it's not running associated with a terminal anymore.

    $ true | echo `tty | sed 's:/dev/::'`
    not a tty
    $ 
    

    Note that nothing in this answer so far is specific to bash. Since you're using bash, another way around this problem is to use process substitution. For example, while this does not work:

    $ who | grep "$(tty | sed 's:/dev/::')"
    

    This does:

    $ grep $(tty | sed 's:/dev/::') < <(who)
    

提交回复
热议问题