数组赋值
列表赋值
用新元素创建数组
- array=('first element' 'second element' 'third element')
下标赋值
显式指定元素索引创建数组:
- array=([3]='fourth element' [4]='fifth element')
按索引赋值
- array[0]='first element'
- array[1]='second element'
按名称赋值(关联数组)
- declare -A array
- array[first]='First element'
- array[second]='Second element'
动态赋值
以其它命令的输出创建一个数组,例如使用seq创建一个从1到10的数组:
从脚本参数创建数组
循环内赋值
- while read -r; do
- #array+=("$REPLY") # Array append
- array[$i]="$REPLY" # Assignment by index
- let i++ # Increment index
- done < <(seq 1 10) # command substitution
- echo ${array[@]} # output: 1 2 3 4 5 6 7 8 9 10
访问数组元素
打印索引为0的元素
打印最后一个元素(从Bash 4.3可用)
打印从索引1开始的元素
打印从索引1开始的3个元素
数组更改
按索引更改
初始化或者更新数组中的一个特定元素
- array[10]="elevenths element" # because it's starting with 0
追回
修改数组,追加元素到数组结尾
- array+=('fourth element' 'fifth element')
添加元素到数组开头
- array=("new element" "${array[@]}")
插入
给定索引值插入一个元素
- arr=(a b c d)
- # insert an element at index 2
- i=2
- arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
- echo "${arr[2]}" #output: new
删除
使用uset删除指定索引元素
- arr=(a b c)
- echo "${arr[@]}" # outputs: a b c
- echo "${!arr[@]}" # outputs: 0 1 2
- unset -v 'arr[1]'
- echo "${arr[@]}" # outputs: a c
- echo "${!arr[@]}" # outputs: 0 2
重排索引
当有一些元素从数组被删除时,可以使用下面方法重排索引,或者你不知道索引是否存在时隙时会有用。
数组长度
${#array[@]}可以得到${array[@]}数组的长度
- array=('first element' 'second element' 'third element')
- echo "${#array[@]}" # gives out a length of 3
迭代数组元素
- fileList=( file1.txt file2.txt file3.txt )
-
- # Within the for loop, $file is the current file
- for file in "${fileList[@]}"
- do
- echo "$file"
- done