根据BASH(4.2.46版本)中的用户输入命名数组



我有一个litle脚本,要求用户命名一个数组,然后向该数组添加元素,但当我尝试使用变量回显数组时,我只得到数组的名称,但如果我使用在提示中输入的实际名称,它会显示数组上的值,我需要在脚本的进一步开发中继续使用用户定义的数组,但如果我不能使用数组的dinamic名称来获取值,那就没有用了。

我无法更新bash,因此无法使用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[@]}"

结果

my_array
4 5 6 7

如果bash版本是4.3或更新版本,则可以使用nameref属性:

declare -n ref=$array_name
echo "${ref[@]}"

最新更新