Shell 数组

数组定义、取值、遍历、长度、追加与关联数组。

Beginner
Key Pointsbash 数组用空格分隔,${arr[@]} 取全部、${#arr[@]} 取长度;关联数组要先 declare -A。

定义与取值

Bash
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"
echo "${fruits[-1]}"
echo "${#fruits[@]}"
echo "${fruits[@]}"
Output
apple
cherry
3
apple banana cherry

遍历

Bash
fruits=("apple" "banana" "cherry")
for f in "${fruits[@]}"; do
    echo "- $f"
done
Output
- apple
- banana
- cherry

Iterate with "${arr[@]}". $arr yields only the first element, and unquoted ${arr[@]} splits elements containing spaces.

追加与切片

Bash
a=(1 2 3)
a+=(4 5)
echo "${a[@]}"
echo "${a[@]:1:3}"
echo "${#a[@]}"
Output
1 2 3 4 5
2 3 4
5

关联数组

Bash
declare -A score
score[alice]=90
score[bob]=85
for k in "${!score[@]}"; do
    echo "$k=${score[$k]}"
done
echo "count=${#score[@]}"
Output
alice=90
bob=85
count=2
Associative array order is unspecified (hash order). Sort the keys yourself if order matters.

按行读文件到数组

Bash
mapfile -t lines < <(printf 'l1\nl2\nl3\n')
echo "${#lines[@]} lines"
echo "${lines[1]}"
Output
3 lines
l2

Friends & Partners