#!/bin/bash string="hello,shell,split,test" #将,替换为空格 array=(${string//,/ }) for var in ${array[@]} do echo $var done
输出
bogon:conf macname$ ./test.sh
hello
shell
split
test
还可以写成
#!/bin/bash string="hello,shell,split,test" array=(`echo $string | tr ',' ' '` ) for var in ${array[@]} do echo $var done
或者
#!/bin/bash string="hello,shell,split,test" #对IFS变量 进行替换处理 OLD_IFS="$IFS" IFS="," array=($string) IFS="$OLD_IFS" for var in ${array[@]} do echo $var done
参考: