Loop through a comma-separated shell variable

前端 未结 8 1941
醉话见心
醉话见心 2020-12-22 18:15

Suppose I have a Unix shell variable as below

variable=abc,def,ghij

I want to extract all the values (abc, def an

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-22 19:08

    If you set a different field separator, you can directly use a for loop:

    IFS=","
    for v in $variable
    do
       # things with "$v" ...
    done
    

    You can also store the values in an array and then loop through it as indicated in How do I split a string on a delimiter in Bash?:

    IFS=, read -ra values <<< "$variable"
    for v in "${values[@]}"
    do
       # things with "$v"
    done
    

    Test

    $ variable="abc,def,ghij"
    $ IFS=","
    $ for v in $variable
    > do
    > echo "var is $v"
    > done
    var is abc
    var is def
    var is ghij
    

    You can find a broader approach in this solution to How to iterate through a comma-separated list and execute a command for each entry.

    Examples on the second approach:

    $ IFS=, read -ra vals <<< "abc,def,ghij"
    $ printf "%s\n" "${vals[@]}"
    abc
    def
    ghij
    $ for v in "${vals[@]}"; do echo "$v --"; done
    abc --
    def --
    ghij --
    

提交回复
热议问题