原理是將變化shell環境下的一個系統變量IFS
#!/bin/bash
function to_array()
{
x=$1
OLD_IFS="$IFS" #默認的IFS值為換行符
IFS=","
array=($x) ?#以逗號進行分割了
IFS="$OLD_IFS" #還原默認換行符
for each in ${array[*]}
do
echo $each
done
}
arr=($(to_array 'a,b,c,d,e'))
echo ${arr[*]}
另外一個例子,介紹IFS的用法。參考shell中的特殊變量IFS
比如,有個文件內容如下:
? ? ? the first line.
the second line.
the third line.
打印每行:
forline in `cat filename`
do
echo $line
done
結果是下面這種一行一個單詞,顯然是不符合預期的:
the
first
line.
the
second
line.
the
third
line.
借助IFS變量進行做個調整:
IFS=$'\n'
for line in `cat k.shfile`
do
echo $line
done
輸出就是正確的:
? ? the first line.
the second line.
the third line.