Loop through a comma-separated shell variable

前端 未结 8 1894
醉话见心
醉话见心 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:03

    You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.

    variable=abc,def,ghij
    for i in $(echo $variable | sed "s/,/ /g")
    do
        # call your procedure/other scripts here below
        echo "$i"
    done
    

    Instead of the echo "$i" call above, between the do and done inside the for loop, you can invoke your procedure proc "$i".


    Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS and then parse your variable.


    Hope this helps.

提交回复
热议问题