0

I have a litle script that ask to the user to name an array and then add elements to that array, but when I try to echo the array using the variable I get only the name of the array, but if I use the actual name that I imput in the prompt it show me the values on the array, I need to keep using that array that the user defines in further developing of the script, but it wont be useful if I cant get the values using dinamic name of the array.

I can't update bash so cant use nameref

#!/bin/bash

# prompt the user to enter the array name
read -p "Enter the name of the array: " array_name
# ===> as the user I enter de name : my_array <=====

# create an empty array with the specified name
declare -a "$array_name"

# prompt the user to enter values for the array
read -p "Enter values for the array, separated by spaces: " -a "$array_name"

# echo the name of the array
echo "${array_name[@]}"

# echo the values of the array
echo "${my_array[@]}"

result

my_array
4 5 6 7

1 Answers1

0

You can use nameref attribute, if your bash version is 4.3 or newer:

declare -n ref=$array_name
echo "${ref[@]}"
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17