Bash使用示例(1) – 数组

数组赋值


列表赋值

用新元素创建数组

  1. array=('first element' 'second element' 'third element')

下标赋值

显式指定元素索引创建数组:

  1. array=([3]='fourth element' [4]='fifth element')

按索引赋值

  1. array[0]='first element'
  2. array[1]='second element'

按名称赋值(关联数组)

  1. declare -A array
  2. array[first]='First element'
  3. array[second]='Second element'

动态赋值

以其它命令的输出创建一个数组,例如使用seq创建一个从1到10的数组:

  1. array=(`seq 1 10`)

从脚本参数创建数组

  1. array=("$@")

循环内赋值

  1. while read -r; do
  2.     #array+=("$REPLY")     # Array append
  3.     array[$i]="$REPLY"     # Assignment by index
  4.     let i++                # Increment index
  5. done < <(seq 1 10)  # command substitution
  6. echo ${array[@]}    # output: 1 2 3 4 5 6 7 8 9 10

访问数组元素


打印索引为0的元素

  1. echo "${array[0]}"

打印最后一个元素(从Bash 4.3可用)

  1. echo "${array[-1]}"

打印从索引1开始的元素

  1. echo "${array[@]:1}"

打印从索引1开始的3个元素

  1. echo "${array[@]:1:3}"

数组更改


按索引更改

初始化或者更新数组中的一个特定元素

  1. array[10]="elevenths element"    # because it's starting with 0

追回

修改数组,追加元素到数组结尾

  1. array+=('fourth element' 'fifth element')

添加元素到数组开头

  1. array=("new element" "${array[@]}")

插入

给定索引值插入一个元素

  1. arr=(a b c d)
  2. # insert an element at index 2
  3. i=2
  4. arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
  5. echo "${arr[2]}" #output: new

删除

使用uset删除指定索引元素

  1. arr=(a b c)
  2. echo "${arr[@]}"   # outputs: a b c
  3. echo "${!arr[@]}"  # outputs: 0 1 2
  4. unset -v 'arr[1]'
  5. echo "${arr[@]}"   # outputs: a c
  6. echo "${!arr[@]}"  # outputs: 0 2

重排索引

当有一些元素从数组被删除时,可以使用下面方法重排索引,或者你不知道索引是否存在时隙时会有用。

  1. array=("${array[@]}")

数组长度



${#array[@]}可以得到${array[@]}数组的长度

  1. array=('first element' 'second element' 'third element')
  2. echo "${#array[@]}" # gives out a length of 3

迭代数组元素


  1. fileList=( file1.txt file2.txt file3.txt )
  2.  
  3. # Within the for loop, $file is the current file
  4. for file in "${fileList[@]}"
  5. do
  6.   echo "$file"
  7. done
标签:Bash 发布于:2019-11-21 03:26:33