2

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

sai akhil
  • 113
  • 4
  • I've found [this question](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) with multiples replies. See if one of then help's you – Marcio Rocha Mar 11 '22 at 12:25
  • 1
    If you have a recent enough version of bash you can use namerefs: `declare -n tmp="${n}_array"; nohup sh test.sh "${tmp[@]}"...`. – Renaud Pacalet Mar 11 '22 at 12:36
  • Also see [BashFAQ/006 (How can I use variable variables (indirect variables, pointers, references) or associative arrays?)](https://mywiki.wooledge.org/BashFAQ/006). – pjh Mar 11 '22 at 13:35

2 Answers2

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
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51
0

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 
pjh
  • 6,388
  • 2
  • 16
  • 17