変数を変数として使用

変数を変数として使用

variablenaamループで使用する変数を使用したいです。私は数時間努力しましたが、うまくいきませんでした。

最新のRaspbianを用いてRPi 4でbash実験を行った。

私はループで使用できるようにxstack1とxstack2変数を使用するのが好きです。次の例では、ループで使用したい2つのスタックがあるため、変数を作成する必要があります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を配列として明示的に宣言する必要があります。

おすすめ記事