向数组追加元素

时间:2021-01-01 10:45:01
向数组追加元素的方法与数组复制非常类似。最简单的追加到数组的方法是将数组复制语句进行扩展。
 
hobbies=( "${activities[@]" diving }
 $  for hobby in "${hobbies[@]}"
do
>    echo "Hobby: $hobby"
done
Hobby: swimming
Hobby: water skiing
Hobby: canoeing
Hobby: white-water rafting
Hobby: surfing
Hobby: scuba diving
Hobby: diving
$
 
本章开头介绍了如何使用seq 0 $((${#beatles[@]}–1))获取数组的最后一个实际元素。但数组从0开始索引这一事实使得这一任务变得有些棘手。在向数组追加单个元素时,数组从0开始索引实际上使得追加操作更容易。
hobbies[${#hobbies[@]}]=rowing
for hobby in "${hobbies[@]}"
do
>    echo "Hobby: $hobby"
done
Hobby: swimming
Hobby: water skiing
Hobby: canoeing
Hobby: white-water rafting
Hobby: surfing
Hobby: scuba diving
Hobby: diving
Hobby: rowing
$
bash shell确实有组合两个数组的内置语法。这种使用C风格符号+=的方法更简洁,而且写出的代码更清晰。
airsports=( flying gliding parachuting )
activities+=("${airsports[@]}")
for act in "${activities[@]}"
do
>    echo "Activity: $act"
done
Activity: swimming
Activity: water skiing
Activity: canoeing
Activity: white-water rafting
Activity: surfing
Activity: scuba diving
Activity: climbing
Activity: walking
Activity: cycling
Activity: flying
Activity: gliding
Activity: parachuting


出处:https://book.2cto.com/201209/3572.html