我对 bash 脚本非常陌生,只是收集脚本所需的所有信息。
我想迭代具有变量名的数组。到目前为止我的脚本:
#!/bin/bash
declare -a bff=("Abnehmen" "Buecher" "Dating" "Dating" "Fitness" "Handy" "Hunde" "Reisen" "Schmuck" "Schwanger" "Uhren")
declare -a dab=("baby" "beauty" "fitness" "haushalt" "heimwekren")
for product in bff dab; do
echo "${product[@]}" #works fine, it echoes 'bff' in the first loop
for sub in ${!product[@]}; do
echo "${product}/${sub}" #does not work, echoes 'bff/0'
done
done
输出:
bff
bff/0
dab
dab/0
ddb
ddb/0
dwb
dwb/0
pod
pod/0
我不明白为什么我可以正确回显变量,但不能在 for 循环中使用它。我发现的教程只是关于回显 varibale 变量,但现在如何在循环中使用它。
有人可以在这里帮助我或指导我正确的方向吗?
我想要的输出是:
bff
bff/Abnehmen
bff/Buecher
bff/Dating
...
dab
dab/baby
dab/beauty
...
答案1
通过以下方式使用变量引用declare -n refvar=$varname
:
#!/bin/bash
declare -a bff=("Abnehmen" "Buecher" "Dating" "Dating" "Fitness" "Handy" "Hunde" "Reisen" "Schmuck" "Schwanger" "Uhren")
declare -a dab=("baby" "beauty" "fitness" "haushalt" "heimwekren")
for product in bff dab; do
echo "${product[@]}" #works fine, it echoes 'bff' in the first loop
declare -n parray=$product
for sub in "${parray[@]}"; do
echo "${product}/${sub}" #does not work, echoes 'bff/0'
done
done
bff
bff/Abnehmen
bff/Buecher
bff/Dating
bff/Dating
bff/Fitness
bff/Handy
bff/Hunde
bff/Reisen
bff/Schmuck
bff/Schwanger
bff/Uhren
dab
dab/baby
dab/beauty
dab/fitness
dab/haushalt
dab/heimwekren