循环使用逗号分隔的shell变量 [英] Loop through a comma-separated shell variable
问题描述
假设我有一个如下的Unix shell变量
Suppose I have a Unix shell variable as below
variable=abc,def,ghij
我想使用for循环提取所有值(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.
该脚本应允许从$variable
中提取任意数量的逗号分隔值.
The script should allow extracting arbitrary number of comma-separated values from $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,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
# call your procedure/other scripts here below
echo "$i"
done
代替上面的echo "$i"
调用,可以在for循环内的do
和done
之间,调用过程proc "$i"
.
Instead of the echo "$i"
call above, between the do
and done
inside the for loop, you can invoke your procedure proc "$i"
.
更新:如果变量的值不包含空格,则以上代码段均适用.如果您有这样的要求,请使用可以更改IFS
的解决方案之一,然后解析您的变量.
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.
希望这会有所帮助.
这篇关于循环使用逗号分隔的shell变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!