我對 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