Home > Enterprise >  Change name of Variable while in a loop
Change name of Variable while in a loop

Time:04-30

I have this idea in mind:

I have this number: CN=20

and a list=( "xa1-" "xa2-" "xb1-" "xb2-")

and this is my script:

for a in "${list[@]}"; do

        let "CN=$(($CN 1))"
        echo $CN

Output:
21
22
23
24

I am trying to create a loop where it creates the following variables, which will be referenced later in my script:

fxp0_$CN="fxp-$a$CN"

fxp0_21="fxp-xa1-21"
fxp0_22="fxp-xa2-22"
fxp0_23="fxp-xb1-23"
fxp0_24="fxp-xb2-24"

However, I have not been able to find a way to change the variable name within my loop. Instead, I was trying myself and I got this error when trying to change the variable name:

scripts/srx_file_check.sh: line 317: fxp0_21=fxp0-xa2-21: command not found

CodePudding user response:

After playing around I found the solution!

for a in "${list[@]}"; do

        let "CN=$(($CN 1))"
        fxp_int="fxp0-$a$CN"
        eval "fxp0_$CN=${fxp_int}"
    done

    echo $fxp0_21
    echo $fxp0_22
    echo $fxp0_23
    echo $fxp0_24
    echo $fxp0_25
    echo $fxp0_26
    echo $fxp0_27
    echo $fxp0_28

Output:

fxp0-xa1-21
fxp0-xa2-22
fxp0-xb1-23
fxp0-xb2-24
fxp0-xc1-25
fxp0-xc2-26
fxp0-xd1-27
fxp0-xd2-28

CodePudding user response:

Since the only thing changing in the variable names is a number we could use a normal (numerically indexed) array, eg:

CN=20
list=("xa1-" "xa2-" "xb1-" "xb2-")

declare -a fxp0=()

for a in "${list[@]}"
do
    (( CN   ))
    fxp0[${CN}]="fxp-${a}${CN}"
done

This generates:

$ declare -p fxp0
declare -a fxp0=([21]="fxp-xa1-21" [22]="fxp-xa2-22" [23]="fxp-xb1-23" [24]="fxp-xb2-24")

$ for i in "${!fxp0[@]}"; do echo "fxp0[$i] = ${fxp0[$i]}"; done
fxp0[21] = fxp-xa1-21
fxp0[22] = fxp-xa2-22
fxp0[23] = fxp-xb1-23
fxp0[24] = fxp-xb2-24

CodePudding user response:

As a general rule can I tell you that it's not a good idea to modify names of variables within loops.

There is, however, a way to do something like that, using the source command, as explained in this URL with some examples. It comes down to the fact that you treat a file as a piece of source code.

Good luck

  • Related