'Dynamic variable in SHELL SCRIPT [duplicate]

I have 3 different array as follows(ignore the actual values)

first_array=(123 456 657)
second_array=(11 22 33)
third_array=(29 45 56)

so i have a case where i need to pass these arrays one by one as an argument to a shell file

sh test.sh "${first_array[@]}"

but what im working on is a for loop as follows

arrays=("first" "second" "third")
for n in ${arrays[@]}; do
   array=${n}_array
   nohup sh test.sh "${!array[@]}" > log_${n} &   <-some error here, array not going in
done 

Please help me on how to write for loop for such case



Solution 1:[1]

If you have a recent enough version of bash you can use namerefs:

for n in ${arrays[@]}; do
  declare -n tmp="${n}_array"
  nohup sh test.sh "${tmp[@]}" > "log_${n}" &
done

Solution 2:[2]

Try this Shellcheck-clean code:

arrays=(first second third)
for n in "${arrays[@]}"; do
    array_ref="${n}_array[@]"
    nohup sh test.sh "${!array_ref}" > "log_$n" &
done 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Renaud Pacalet
Solution 2 pjh