0

(bash noobie here)

In bash I am successful creating an array with database tables and then looping through them. I want to declare this array at the top of my script and then assign it later to another variable.

my_databases=(value1 value2 value3)

Looping through this works fine with for i in "${my_databases[@]}"

The problem is here: Instead of looping through my_databases I have a step in between and I want to assign the array to a variable new_array.

new_array=$my_databases

Now when I loop through this new_array, the script fails after the first array value. How can I assign a declared array to a new variable correctly?

2 Answers 2

3

To create a new array variable, assign the values of the old array to the new array like this:

my_databases=(value1 value2 value3)
new_array=("${my_databases[@]}")

If you use

new_array=$my_databases

the new variable will not be an array (unless you use declare -a new_array=$my_databases) and $my_databases only expands to the first value of the array.

3
  • bash handles this new_array=$my_databases like this: new_array=${my_databases[0]} Sep 30, 2019 at 17:39
  • Thanks. I played with the other comment as well to see what happens. Works great!
    – Daniel
    Sep 30, 2019 at 18:24
  • 1
    @Daniel When debugging it can help to display the attributes and values of the variables with declare -p name […] like declare -p my_databases new_array.
    – Freddy
    Sep 30, 2019 at 18:29
3

I assume you want to create a copy of the array. Then use @Freddy's answer.

If you want to create a reference to the same data, recent versions of bash have "namerefs":

$ my_databases=(value1 value2 value3)
$ declare -n new_array=my_databases

Then:

$ for i in "${!new_array[@]}"; do printf "%d\t%s\n" $i "${new_array[i]}"; done
0   value1
1   value2
2   value3

but if you alter the first array, the changes are seen in the "new" one:

$ my_databases[2]="updated value 3"
$ for i in "${!new_array[@]}"; do printf "%d\t%s\n" $i "${new_array[i]}"; done
0   value1
1   value2
2   updated value 3
1
  • Thanks. I like this. Good for manipulation of the array. Thanks for sharing hat.
    – Daniel
    Sep 30, 2019 at 18:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .