In a Linux shell how can I process each line of a multiline string?

后端 未结 6 572
情深已故
情深已故 2021-01-31 17:24

While in a Linux shell I have a string which has the following contents:

cat
dog
bird

and I want to pass each item as an argument to another fu

6条回答
  •  遥遥无期
    2021-01-31 18:17

    Just pass your string to your function:

    function my_function
    {
        while test $# -gt 0
        do
            echo "do something with $1"
            shift
        done
    }
    my_string="cat
    dog
    bird"
    my_function $my_string
    

    gives you:

    do something with cat
    do something with dog
    do something with bird
    

    And if you really care about other whitespaces being taken as argument separators, first set your IFS:

    IFS="
    "
    my_string="cat and kittens
    dog
    bird"
    my_function $my_string
    

    to get:

    do something with cat and kittens
    do something with dog
    do something with bird
    

    Do not forget to unset IFS after that.

提交回复
热议问题