上一篇
在 Linux Shell脚本编程 中,数组是一种非常实用的数据结构,它允许我们将多个值存储在一个变量中。虽然 Bash(最常用的 Shell)中的数组功能不如高级语言强大,但掌握其基本用法和常用“库函数”(即封装好的操作函数)能极大提升脚本编写效率。

Bash 支持一维索引数组(从 0 开始)和关联数组(类似字典,Bash 4.0+ 支持)。本文主要讲解索引数组,因其兼容性更好。
# 方法1:逐个赋值arr[0]="apple"arr[1]="banana"arr[2]="cherry"# 方法2:一次性定义arr=("apple" "banana" "cherry")# 方法3:使用 declare 声明(可选)declare -a arr=("apple" "banana" "cherry")echo ${arr[0]} # 输出 appleecho ${arr[@]} # 输出所有元素:apple banana cherryecho ${#arr[@]} # 输出数组长度:3虽然 Shell 没有官方“标准库”,但我们可以通过自定义函数来模拟常用操作。以下是几个高频使用的 Shell数组函数:
array_length() { local arr_name="$1" local -n ref_arr="$arr_name" echo ${#ref_arr[@]}}# 使用示例fruits=("apple" "banana" "cherry")len=$(array_length fruits)echo "数组长度为: $len" # 输出 3注意:local -n是 Bash 4.3+ 的 nameref 功能,用于间接引用数组。若环境较旧,可直接使用${#arr[@]}。
array_contains() { local e match="$1" shift for e; do [[ "$e" == "$match" ]] && return 0; done return 1}# 使用示例fruits=("apple" "banana" "cherry")if array_contains "banana" "${fruits[@]}"; then echo "找到了香蕉!"fiarray_push() { local arr_name="$1" local value="$2" local -n ref_arr="$arr_name" ref_arr+=("$value")}# 使用示例declare -a colorsarray_push colors "red"array_push colors "green"echo ${colors[@]} # 输出 red greenarray_remove() { local arr_name="$1" local index="$2" local -n ref_arr="$arr_name" unset ref_arr[$index] # 可选:重建连续索引 ref_arr=(${ref_arr[@]})}# 使用示例nums=(10 20 30 40)array_remove nums 1echo ${nums[@]} # 输出 10 30 40${arr[@]} 会按索引顺序输出。"${arr[@]}"),避免单词分割问题。通过自定义函数,我们可以将常见的 Shell数组操作 封装成“库函数”,提高脚本的可读性和复用性。虽然 Bash 的数组功能有限,但只要掌握基础语法和这些实用技巧,就能应对大多数自动化任务需求。
希望这篇教程能帮助你轻松上手 Shell脚本编程 中的数组操作!
本文由主机测评网于2025-11-30发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025111310.html