Section 12.1: 数组赋值

列表赋值

如果你熟悉 Perl、C 或 Java,你可能会认为 Bash 会使用逗号来分隔数组元素,但事实并非如此;相反,Bash 使用空格:

# Array in Perl
my @array = (1, 2, 3, 4);
# Array in Bash
array=(1 2 3 4)

创建一个包含新元素的数组:

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

下标赋值

创建一个具有明确元素索引的数组:

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

按索引赋值

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

按名称赋值(关联数组)

Version ≥ 4.0

declare -A array
array[first]='First element'
array[second]='Second element'

动态赋值

从其他命令的输出中创建数组,例如使用 seq 获取 1 到 10 的范围:

array=(`seq 1 10`)

根据脚本输入参数赋值:

array=("$@")

循环内赋值

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

其中 $REPLY 始终是当前的输入值

Section 12.2: 访问数组元素

打印索引 0 的元素

echo "${array[0]}"

Version < 4.3

使用子字符串扩展语法打印最后一个元素

echo "${arr[@]: -1 }"

Version ≥ 4.3

使用下标语法打印最后一个元素

echo "${array[-1]}"

打印所有元素,每个元素单独引用

echo "${array[@]}"

以单引号字符串的形式打印所有元素

echo "${array[*]}"

打印从索引 1 开始的所有元素,每个元素单独引用

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

打印从索引 1开始 3 个元素,每个元素单独引用

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

字符串操作

如果引用单个元素中的字符串,则允许进行字符串操作:

array=(zero one two)
echo "${array[0]:0:3}" # gives out zer (chars at position 0, 1 and 2 in the string zero)
echo "${array[0]:1:3}" # gives out ero (chars at position 1, 2 and 3 in the string zero)

因此,${array[$i]:N:M} 从字符串${array[$i]} 中的第 N 个位置(从 0 开始)给出一个字符串,后面有 M 个字符。

Section 12.3: 数组的修改

更改索引

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

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

Version ≥ 3.1

添加

修改数组,如果没有指定下标,则在末尾添加元素。

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

将新的参数追加到数组后面。

array=("${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

删除

使用 unset 内置函数删除数组索引:

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

合并

array3=("${array1[@]}" "${array2[@]}")

这也适用于稀疏数组。

重新索引数组

如果元素已从数组中移除,或者不确定数组中是否存在间隙,这将非常有用。要重新创建没有间隙的索引,请执行以下操作

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

Section 12.4: 数组迭代

数组迭代有两种形式:foreach 和经典的 for 循环:

a=(1 2 3 4)
# foreach 循环
for y in "${a[@]}"; do
    # act on $y
    echo "$y"
done
# 经典的 for 循环
for ((idx=0; idx < ${#a[@]}; ++idx)); do
    # act on ${a[$idx]}
    echo "${a[$idx]}"
done

您还可以遍历命令的输出:

a=($(tr ',' ' ' <<<"a,b,c,d")) # tr can transform one character to another
for y in "${a[@]}"; do
    echo "$y"
done

Section 12.5: 阵列长度

${#array[@]} 给出了数组 ${array[@]} 的长度:

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

这也适用于单个元素中的字符串:

echo "${#array[0]}" # gives out the lenght of the string at element 0: 13

Section 12.6: 关联数组

Version ≥ 4.0

声明一个关联数组

declare -A aa

在初始化或使用关联数组之前,必须先声明关联数组。

初始化元素

可以按如下方式逐个初始化元素:

aa[hello]=world
aa[ab]=cd
aa["key with space"]="hello world"

您也可以在一条语句中初始化整个关联数组:

aa=([hello]=world [ab]=cd ["key with space"]="hello world")

访问关联数组元素

echo ${aa[hello]}
# Out: world

列出关联数组键

echo "${!aa[@]}"
#Out: hello ab key with space

列出关联数组值

echo "${aa[@]}"
#Out: world cd hello world

对关联数组的键和值进行遍历

for key in "${!aa[@]}"; do
echo "Key: ${key}"
echo "Value: ${array[$key]}"
done
# Out:
# Key: hello
# Value: world
# Key: ab
# Value: cd
# Key: key with space
# Value: hello world

关联数组元素计数

echo "${#aa[@]}"
# Out: 3

Section 12.7: 循环浏览数组

我们的示例数组

arr=(a b c d e f)

使用 for...in 循环:

for i in "${arr[@]}"; do
        echo "$i"
done

Version ≥ 2.04

使用 C 风格 for 循环:

for ((i=0;i<${#arr[@]};i++)); do
        echo "${arr[$i]}"
done

使用 while 循环:

i=0
while [ $i -lt ${#arr[@]} ]; do
    echo "${arr[$i]}"
    i=$((i + 1))
done

Version ≥ 2.04

使用带数字条件的 while 循环:

i=0
while (( $i < ${#arr[@]} )); do
    echo "${arr[$i]}"
    ((i++))
done

使用 until 循环:

i=0
until [ $i -ge ${#arr[@]} ]; do
echo "${arr[$i]}"
    i=$((i + 1))
done

Version ≥ 2.04

使用带有数值条件的 until 循环:

i=0
until (( $i >= ${#arr[@]} )); do
echo "${arr[$i]}"
        ((i++))
done

Section 12.8: 销毁、删除或取消设置数组

销毁、删除或取消设置数组:

unset array

销毁、删除或取消设置单个数组元素:

unset array[10]

Section 12.9: 字符串数组

stringVar="Apple Orange Banana Mango"
arrayVar=(${stringVar// / })

字符串中的每一个空格都代表目标数组中的一个新元素。

echo ${arrayVar[0]} # will print Apple
echo ${arrayVar[3]} # will print Mango

同样,也可以使用其他字符作为分隔符。

stringVar="Apple+Orange+Banana+Mango"
arrayVar=(${stringVar//+/ })
echo ${arrayVar[0]} # will print Apple
echo ${arrayVar[2]} # will print Banana

Section 12.10: 初始化索引列表

获取数组中的初始化索引列表

$ arr[2]='second'
$ arr[10]='tenth'
$ arr[25]='twenty five'
$ echo ${!arr[@]}
2 10 25

Section 12.11: 将整个文件读入数组

一步到位的读取:

IFS=$'\n' read -r -a arr < file

使用循环的读取:

arr=()
while IFS= read -r line; do
        arr+=("$line")
done

Version ≥ 4.0

使用 mapfile 或 readarray(两者同义):

mapfile -t arr < file
readarray -t arr < file

Section 12.12: 数组插入功能

此函数将在给定索引处向数组中插入一个元素:

insert(){
    h='
    ################## insert ########################
    # Usage:
    # insert arr_name index element
    #
    # Parameters:
    # arr_name : Name of the array variable
    # index : Index to insert at
    # element : Element to insert
    ##################################################
    '
    [[ $1 = -h ]] && { echo "$h" >/dev/stderr; return 1; }
    declare -n __arr__=$1 # reference to the array variable
    i=$2 # index to insert at
    el="$3" # element to insert
    # handle errors
    [[ ! "$i" =~ ^[0-9]+$ ]] && { echo "E: insert: index must be a valid integer" >/dev/stderr; return 1; }
    (( $1 < 0 )) && { echo "E: insert: index can not be negative" >/dev/stderr; return 1; }
    # Now insert $el at $i
    __arr__=("${__arr__[@]:0:$i}" "$el" "${__arr__[@]:$i}")
}

使用方法:

insert array_variable_name index element

例如:

arr=(a b c d)
echo "${arr[2]}" # output: c
# Now call the insert function and pass the array variable name,
# index to insert at
# and the element to insert
insert arr 2 'New Element'
# 'New Element' was inserted at index 2 in arr, now print them
echo "${arr[2]}" # output: New Element
echo "${arr[3]}" # output: c