我想使用一个变量variablenaam
在循环中使用。我尝试了几个小时但无法使其工作。
我在带有最新 Raspbian 的 RPi 4 上进行了 bash 实验。
我喜欢使用 xstack1 和 xstack2 变量,这样我就可以在循环中使用它们。下面的示例有两个我喜欢在循环中使用的堆栈,因此我必须创建变量xstack<value> variable
。
clear
xstack1=( domoticz dashboard dashticz nodered )
xstack2=( x y z )
printf "Original value xstack1[*]= ${xstack1[*]}" # this gives all the entries of x, this must be the result at the end by choose for xstack1 = q=1
printf "\n\n Lets Start, try to make xstack variable"
q=1 # we want tot retrieve all values of xstack1
qq=$(eval "echo xstack${q}")
printf "\nvariablenaame of xstack1 = $qq" # so far so good
printf "\n"
qqq=$(eval "echo $qq[*]") #now add the all parameter
printf "\nvariablenaam with wildcard must do show all values but dont= $qqq" #only one value
printf "\n\n"
qqqq=$(eval "echo \$$qqq")
printf "last try and does not work, i only get one value= ${qqqq}\n"
这是我想使用它的代码。您会看到 stack1-4 的类似块,我认为这可能是一个变量名称为 xstack1-4 的块。这个 xstack 是一个数组,我认为这给出了问题。这些块工作完美,但编写得并不完美:-)
local t_maxkolom=9
local t_mitem=1
local t_stack=0
while [ $t_stack -lt $t_maxkolom ]
do
local t_gitem=0
local t_sp='%31s'
if [ -z "${stack1[$t_stack]}" ]; then printf $t_sp && printf "${normal}"; else
printf "${number} $((t_mitem + $t_gitem )))${normal} Toevoegen " && printf '%-16s' "${stack1[$t_stack]}" && printf "${normal}"
fi
local t_sp='%32s'
local t_gitem=$((t_gitem + 10))
if [ -z "${stack2[$t_stack]}" ]; then printf $t_sp && printf "${normal}"; else
printf "${number} $((t_mitem + $t_gitem )))${normal} Toevoegen " && printf '%-16s' "${stack2[$t_stack]}" && printf "${normal}"
fi
local t_sp='%32s'
local t_gitem=$((t_gitem + 10))
if [ -z "${stack3[$t_stack]}" ]; then printf $t_sp && printf "${normal}"; else
printf "${number} $((t_mitem + $t_gitem )))${normal} Toevoegen " && printf '%-16s' "${stack3[$t_stack]}" && printf "${normal}"
fi
local t_sp='%32s'
local t_gitem=$((t_gitem + 10))
if [ -z "${stack4[$t_stack]}" ]; then printf $t_sp && printf "${normal}\n"; else
printf "${number} $((t_mitem + $t_gitem )))${normal} Toevoegen " && printf '%-16s' "${stack4[$t_stack]}" && printf "${normal}"
printf "\n"
fi
t_stack=$(( $t_stack + 1 ))
t_mitem=$((t_mitem + 1))
done
使用此代码,我为我的 docker 应用程序生成菜单项
答案1
举例来说这个...
xstack1=( domoticz dashboard dashticz nodered )
xstack2=( x y z )
q=1
declare -n qq="xstack${q}"
qqq="${qq[*]}"
echo "q=[$q]"
echo "qq=[$qq]"
echo "qqq=[$qqq]"
产生这个
q=[1]
qq=[domoticz]
qqq=[domoticz dashboard dashticz nodered]
您必须显式地将 nameref 声明为数组。