shellloopsunixfor-loopcut

Loop through a comma-separated shell variable


Suppose I have a Unix shell variable as below

variable=abc,def,ghij

I want to extract all the values (abc, def and ghij) using a for loop and pass each value into a procedure.

The script should allow extracting arbitrary number of comma-separated values from $variable.


Solution

  • 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.