Home > front end >  Dynamic variable name changing in a loop
Dynamic variable name changing in a loop

Time:02-05

I am trying to get the user input a first time with read and get the input into the n2 variable, and then when the loop restarts ask the same read question but this time store the answer in the variable n3 and have the n# variable increment every time the loop restarts.

function addition(){
    read -ep 'How many numbers in the equation?: ' amount

    if [ $amount -ge 2 ]
        then
            read -ep 'First number of the addition?: ' n1
            until [ $count = $amount ]
            do
                number=n$((inc  )) 
                read -ep 'Next number for the addition?: ' n2
            done
        else
            echo "Invalid amount. Must be at minimum 2"
    fi
}

CodePudding user response:

If your bash is recent enough you can use namerefs:

function foo {
  for (( i = 1; i <= 3; i   )); do
    local -n number="n$i"
    number="$i"
  done
  printf '%s %s %s\n' "$n1" "$n2" "$n3" 
}

Demo:

$ foo
1 2 3

If you want to export the nX variables to the global scope just add the g attribute to the local declaration:

local -ng number="n$i"

And then:

$ foo
1 2 3
$ echo "$n1 $n2 $n3"
1 2 3

Note that a bash array doesn't have a limit to its size (apart the physical limit of the available computer memory):

function foo {
  local -ag n=()
  for (( i = 1; i <= $1; i   )); do
    n =("$i")
  done
}

And:

$ foo 5
$ printf '%s\n' "${n[*]}"
1 2 3 4 5
$ for (( i=0; i<${#n[@]}; i   )); do printf '%s ' "${n[i]}"; done; printf '\n'
1 2 3 4 5 
$ for val in "${n[@]}"; do printf '%s ' "$val"; done; printf '\n'
1 2 3 4 5 

We could even mix the two approaches and pass the name of the array as first argument:

function foo {
  unset n
  unset -n n
  local -ng n=$1
  for (( i = 1; i <= $2; i   )); do
    n =("$i")
  done
}

And:

$ foo myArray 7
$ printf '%s\n' "${myArray[*]}"
1 2 3 4 5 6 7
  •  Tags:  
  • Related