上一篇
在 Linux Shell 脚本中,数组是一种非常实用的数据结构,尤其在 Bash 中。然而,很多初学者对如何高效地操作和转换 Shell 数组感到困惑。本文将带你从基础入手,逐步掌握Linux Shell数组的各种转换方法,即使是小白也能轻松上手!
在 Bash 中,数组是一种可以存储多个值的变量。它分为两种类型:
最简单的创建方式如下:
# 索引数组fruits=("apple" "banana" "cherry")# 或者逐个赋值nums[0]=10nums[1]=20nums[2]=30# 关联数组(需 declare -A)declare -A personperson[name]="Alice"person[age]=25 下面我们将介绍几个实用的数组转换技巧,帮助你在脚本中灵活处理数据。
arr=("one" "two" "three")str="${arr[*]}" # 结果: one two threeecho "$str" data="red,green,blue"IFS=',' read -ra color_array <<< "$data"# color_array 现在是 ("red" "green" "blue")# 打印验证declare -p color_array original=("a" "b" "a" "c" "b")declare -A seenunique=()for item in "${original[@]}"; do if [[ -z ${seen[$item]} ]]; then unique+=("$item") seen[$item]=1 fidoneecho "去重后: ${unique[*]}" # 输出: a b c arr=("x" "y" "z")(IFS=","; echo "${arr[*]}") # 输出: x,y,z 我们可以封装一个函数,实现“字符串 → 数组”和“数组 → 字符串”的双向转换:
# 函数:字符串转数组str_to_array() { local str="$1" local delimiter="${2:- }" # 默认空格 local -n arr_ref="$3" # 使用 nameref 引用传入的数组名 IFS="$delimiter" read -ra arr_ref <<< "$str"}# 函数:数组转字符串array_to_str() { local -n arr_ref="$1" local delimiter="${2:- }" local IFS="$delimiter" echo "${arr_ref[*]}"}# 使用示例my_str="10,20,30,40"str_to_array "$my_str" "," my_arrayecho "数组内容: ${my_array[@]}"result=$(array_to_str my_array " | ")echo "拼接结果: $result" # 输出: 10 | 20 | 30 | 40 "${arr[@]}" 来安全引用所有元素(保留空格和特殊字符)。$arr,它只返回第一个元素。通过本文,你已经掌握了Bash数组操作的核心转换技巧。无论是日志处理、配置解析还是自动化脚本,这些Shell脚本编程中的数组转换方法都能大幅提升你的效率。快去实践吧!
本文由主机测评网于2025-11-30发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/2025111316.html