Linuxshell 支持列表数据结构吗?

这个问题和 Shell 支持设置吗?不一样

我知道很多脚本语言支持列表结构,比如 python、 python、 Ruby 和 javascript,那么 linux shell 呢?

Shell 支持这样的语法吗?

for i in list:
do
print i
done

我会首先对 初始化列表,例如:

ListName = [ item1, item2, ..., itemn ]

然后迭代它

在编写 shell 脚本时这可能吗?

216492 次浏览

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
echo "$i"
done


list='"item 1" "item 2" "item 3"'
for i in $list; do
echo $i
done
for i in "$list"; do
echo $i
done
for i in ${array[@]}; do
echo $i
done