Shell 数组
数组定义、取值、遍历、长度、追加与关联数组。
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"
doneOutput
- apple
- banana
- cherryIterate 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=2Associative 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定义与取值
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"
doneOutput
- apple
- banana
- cherry遍历数组必须写 "${arr[@]}"。写成 $arr 只会拿到第一个元素,写成 ${arr[@]} 不加引号,元素里有空格就会被拆开。
追加与切片
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关联数组的遍历顺序不保证(哈希序)。需要固定顺序就自己排序 key,别依赖默认输出。
按行读文件到数组
Bash
mapfile -t lines < <(printf 'l1\nl2\nl3\n')
echo "${#lines[@]} lines"
echo "${lines[1]}"Output
3 lines
l2