0

I have an array of 24 elements stored under the array mba_ext.

echo ${mba_ext[13]} gives me expected results.

Now I have created a variable temp="mba_ext"

Now I am trying to copy contents of the array to another array by making use of temp variable. I wrote the code as shown below:

new_array=$(eval echo '$'{${temp}[@]})

When I give echo$new_array I am getting all contents of array getting printed without any index.

When I give echo ${new_array[4]} I am getting no results. Ideally this command should print the content at index location 4.

Can some please help?

  • Why is eval being used? also you have not used any array by doing temp="mba_ext" – Jetchisel Mar 15 at 5:39
  • What if I want to pass mba_ext as a variable and not directly? temp is a variable that should hold name of the array and not the array itself. And I want to pass the variable name to code. – Mohammed Haleem S Mar 15 at 6:49
1

Based on this answer on Super User.

You can use variable indirection with a proper array […]. The tricky thing is that you have to include the array element (or [@] for all elements) in the variable you're indirecting through.

Example code with the names you used:

mba_ext=('normal' 'with space' 'double"quote' "single'quote" $'new-\n-line' '\backslash')
temp="mba_ext"
temparray="${temp}[@]"   # This includes the array name AND "[@]"
new_array=("${!temparray}")
printf '<%s>\n' "${new_array[@]}"
| improve this answer | |
  • The temp variable is an unnecessary step, but the ! part is key here. – glenn jackman Mar 15 at 12:31
  • The above solution works perfectly fine. Now I have one small query on top of that. Assume I am declaring variable x as temp_array. i.e., x="temp_array" So as per the answer given above i am expecting something like below to be shown $x="${temp[@]}" But its throwing error. Could you please help me with the error? – Mohammed Haleem S Mar 15 at 12:51
  • declare arrayClone=("${temparray[@]}") --> Works fine declare $type=("${temparray[@]}") --> -bash: syntax error near unexpected token `(' Note: variable type="arrayClone" Can you help me how can i rectify the second line of code @kamil-maciorowski – Mohammed Haleem S Mar 15 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.