Bash脚本遍历数组

:names=( Jennifer Tonya Anna Sadie )

The following expression evaluates into all values of the array:

下面的表达式表示一个数组的所有值

${names[@]}

It also can be used anywhere a variable or string can be used.

A simple for loop can iterate through this array one value at a time:

for name in ${names[@]} do

echo $name

# other stuff on $name

done

This script will loop through the array values and print them out, one per line. Additional statements can be placed within the loop body to take further action, such as modifying each file in an array of filenames.

扫描二维码关注公众号,回复: 3081766 查看本文章

Sometimes it is useful to loop through an array and know the numeric index of the array you are using (for example, so that you can reference another array with the same index). The same loop in the example above can be achieved this way, too:

${#names[@]} 表示数组长度

for (( i = 0 ; i < ${#names[@]} ; i++ )) do

echo ${names[$i]}

# yadda yadda

done

In this example, the value ${#names[@]} evaluates into the number of elements in the array (4 in this case). The individual elements of the array are accessed, one at a time, using the index integer $i as ${names[$i]}

猜你喜欢

转载自blog.csdn.net/lwhsyit/article/details/82531250
今日推荐