Loop through a comma-separated shell variable
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,ghijfor 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.
If you set a different field separator, you can directly use a for
loop:
IFS=","for v in $variabledo # 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"> donevar is abcvar is defvar 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[@]}"abcdefghij$ for v in "${vals[@]}"; do echo "$v --"; doneabc --def --ghij --