我编写此代码是为了循环访问 LAN 上的用户名和域。遗憾的是,脚本没有打印任何内容。
#!/bin/bash
construct_array_of_trgts() {
declare -A usrs_n_dmns
local -a guest_dmns
local -a usrs=("j" "jim" "o" "root")
local -a guest_dmns=("raspberrypi" "lenovo")
for d in "${guest_dmns[@]}"; do
PS3="Select the users to include for sshing into $d. Q when done selecting."$'\n'
local -a targt_usrs
select u in "${usrs[@]}"; do
if [[ "$u" ]]; then
targt_usrs+=("$u")
elif [[ "$REPLY" == 'q' ]]; then
break;
fi
done
usrs_n_dmns["${d}"]="$targt_usrs"
done
}
construct_array_of_trgts
for d in "${!usrs_n_dmns[@]}"; do
targt_usrs=("${usrs_n_dmns["${d}"]}")
echo "$usrs_n_dmns"
for u in "${targt_usrs[@]}"; do
echo "ssh ${u}@${d}"
done
done
为什么这个脚本不打印任何可见的东西?数组是否有可能成为 Bash 中关联数组中的值?
如何在 Bash 中迭代值是数组的关联数组?
这是不可能的,因为关联数组值不能是数组。
为什么这个脚本不打印任何可见的内容?
construct_array_of_trgts() {
declare -A usrs_n_dmns
函数体内的declare
等于local
。变量 usrs_n_dmns
是 local
函数中的 construct_array_of_trgts
。 construct_array_of_trgts
返回后,usrs_n_dmns
不再存在。
如果您希望变量是全局变量,请将
-g
添加到 declare
。
数组是否有可能成为 Bash 中关联数组中的值?
没有。