在bash shell 函数传递数组的问题2
在bash shell 函数传递数组的问题2
引入 nameref
特性,bash shell 版本 较新的版本 ,可以使用 nameref
来解决 数组传递的问题。
在函数中如何 传递 传递数组变量
# !/bin/bash
# array variable to function test
#
function testit {# 定义变量 local newarray# 重新构建一个新的数组 # newarray=(`echo "$@"`)newarray=("$@")echo "The new array value is: ${newarray[*]}"
}myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
# 注意这里传递方式 是把整个数组进行传递
testit ${myarray[*]}
testit "${myarray[@]}"
这种方式 就是把整个数组全部进入传入, 在函数内部重新构建 这个数组。 缺点也很明显,如果我需要传递两个数组呢? 如果想传递两个变量,有数组和其他的变量呢?
如果你的shell 版本 大于等于5.0 ,可以支持 nameref 变量引用
# 查看 bash version
bash --version |head -n1
GNU bash, version 5.2.37(1)-release (x86_64-apple-darwin22.6.0)
nameref
特性是在 Bash 4.3 版本中引入的。这个特性允许你创建一个变量作为另一个变量的引用,从而可以通过该引用变量来间接访问和修改目标变量的值。
#!/bin/bashfunction testit {# 接受 数组名 需要使用 -n 这个选项 local -n thisarray="${1}" # 传递给函数的是数组名,所以使用 -n 参数,nameref 变量引用 echo "The received array is ${thisarray[*]}"
}myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
# 传递给函数的是数组名,所以使用 -n 参数,nameref 变量引用
# $myarray 只会取数组第一个元素的值,也就是 1 是不对的....
testit myarray
真实的样例
我希望删除 不同命名空间的 相同的secret , 这个命名空间和secrets 就是两个不同的数组,如果每一个都重复写,脚本就需要 写 M* N 个命令, 所以我想通过数组的形式 传入的function 中 来执行删除操作。
#!/bin/bash
# description: 删除指定命名空间下的指定 Secret, 需要Bash 4.3 及以上版本中才引入的 nameref 特性
# bash --version |head -n1
# GNU bash, version 5.2.37(1)-release (x86_64-apple-darwin22.6.0)
# author: frank
# date: 2025-07-03
# usage: bash delete_secret_senior.sh# 函数定义:批量删除多个命名空间中的 Secrets
delete_secrets_in_namespaces() {local -n secrets_array=$1 # 使用 nameref 引用传入的 Secret 数组local -n namespaces_array=$2 # 使用 nameref 引用传入的 Namespace 数组for ns in "${namespaces_array[@]}"; doecho "Processing namespace: ${ns}"for secret in "${secrets_array[@]}"; doif kubectl get secret "${secret}" -n "${ns}" &> /dev/null; thenecho "Deleting secret '${secret}' in namespace '${ns}'..."# debug,not execute true command# kubectl delete secret "${secret}" -n "${ns}"if [ $? -eq 0 ]; thenecho "✅ Secret '${secret}' deleted successfully from namespace '${ns}'."elseecho "❌ Failed to delete secret '${secret}' from namespace '${ns}'."fielseecho "⚠️ Secret '${secret}' not found in namespace '${ns}', skipping deletion."fidonedone
}# 定义要删除的 Secret 名称数组
SECRETS=("acr-zhihe-secret-public" "acr-zhihe-secret-internal")# 定义命名空间数组(支持多个)
NAMESPACES=("dev" "test" "prod" )# 调用函数
delete_secrets_in_namespaces SECRETS NAMESPACESecho "Secret deletion process completed."
总结:
shell 脚本中数组作为函数参数, 如果bash shell 版本 在5.0 以上 ,可以使用nameref
特性 会比较方便一点。 不需要重新创建数组 来解决数组在函数中作为参数的问题。