Understanding the UNIX command xargs

前端 未结 5 853
[愿得一人]
[愿得一人] 2021-01-31 16:37

I\'m pretty much confused on this. Need some clarifications.

Example 1 :

pgrep string | xargs ps

Example 2 :

5条回答
  •  春和景丽
    2021-01-31 17:21

    #!/bin/sh
    #script to echo out the arguments 1 at a time!
    for a in $*
    do
        echo $a
    done
    

    the command

    $sh myscript 1 2 3 4 5
    

    will yield

    1
    2
    3
    4
    5
    

    but

    $sh myscript 1 2 3 4 5 6 7 8 9 10 11
    

    will not work since the max number of parameters is exceeded (im not actually sure what the max is, but lets say its 10 for this example!)

    To get around this we could use

    #!/bin/sh
    #script to echo out the arguments 1 at a time!
    for a in $*
    do
        echo $a | xargs echo
    done
    

    we could then run it like this

     $sh myscript "1 2 3 4 5" "6 7 8 9 10 11"
    

    and get the correct result since there are just 2 parameters

提交回复
热议问题