Home > OS >  Bash, create multiple arrays with different names using loops
Bash, create multiple arrays with different names using loops

Time:02-16

I'm currently learning script shell programming(bash), and trying to make multiple arrays with different names by looping so that I could put the data according to the length of my data files. I've done getting the length of the data file(marked as 'num'), and here's what I could think in my brain.

for (( i=0; i<num; i   ))
do  
    let array$i=()
done

I've looked up many method but it didn't work. I'm a newbie to bash so any comments / recommendations / teachings would be so appreciated. Thank you.

CodePudding user response:

With a recent enough bash, using namerefs:

for (( i=0; i<num; i   )); do  
  declare -n nr="array$i"
  declare -a nr=()
done

And then, each time you want to add elements to your array10:

i=10
declare -n nr="array$i"
nr =( foo bar )

To access the elements you can use the nameref (nr) or the array name, it works the same (as long as you do not modify the nameref attribute):

$ i=10
$ declare -n nr="array$i"
$ printf '%s\n' "${nr[@]}"
foo
bar
$ printf '%s\n' "${array10[@]}"
foo
bar

Think of it as a kind of reference.

  • Related