Bash:循环列表(数组的数组)并访问子列表值

问题描述 投票:0回答:1

在 BASH 中,考虑一个(伪)结构化数组列表,如下所示:

## all my arrays definitions:
myArray1=("userList1" "emailList1" "valueList1")
myArray2=("userList2" "emailList2" "valueList2")
...
myArrayN=("userListN" "emailListN" "valueListN")

## a list of the arrays I need to loop through:
active_lists=("myArray1" "myArray2" [... "myArrayN"])

我想循环遍历我在

active_lists
collection 中配置的每个数组。

这在教程中经常提到,人们会认为以下内容可以解决问题:

for indexd in "${active_lists[@]}"; do
   username=${!indexd}[0]
   email=${!indexd}[1]
   echo "Email: ${email}, username: ${username}"
done

将所有这些放入 Bash 脚本(启用严格模式)应该是最简单的:

#!/bin/bash

set -euo pipefail

declare -a myArray1=("userList1" "emailList1" "valueList1")
declare -a myArray2=("userList2" "emailList2" "valueList2")

declare -a active_lists=("myArray1" "myArray2")

for indexd in "${active_lists[@]}"; do
   username=${!indexd}[2]
   email=${!indexd}[1]
   echo "Email: ${email}, username: ${username}"

   sublist=(${!indexd})
   echo "List Value: ${sublist[1]}"
done

但是,运行上述脚本会导致元素名称的文字打印,或者在尝试访问子列表中的索引时出现

unbound variable
警告:

Email: userList1[1], username: userList1[2]
Email: userList2[1], username: userList2[2]

line 16: sublist[1]: unbound variable

这应该是简单的 AF,我显然错过了一些基本的东西,但我无法弄清楚那是什么,我要疯了!请帮忙。

bash shell sh
1个回答
0
投票

通过

bash 4.3+
,您可以使用 nameref 循环访问不同的数组。

一个

bash
方法:

myArray1=("userList1" "emailList1" "valueList1")
myArray2=("userList2" "emailList2" "valueList2")
myArrayN=("userListN" "emailListN" "valueListN")

active_lists=("myArray1" "myArray2" "myArrayN")

for arr_name in "${active_lists[@]}"
do
    printf "\n####### ${arr_name}\n\n"

    declare -n _arr="${arr_name}"                      # nameref

    for i in "${!_arr[@]}"                             # refer to nameref variable "_arr[]" to access the current "arr_name"
    do
        echo "${arr_name}[$i] = ${_arr[i]}"
    done
done

这会生成:

####### myArray1

myArray1[0] = userList1
myArray1[1] = emailList1
myArray1[2] = valueList1

####### myArray2

myArray2[0] = userList2
myArray2[1] = emailList2
myArray2[2] = valueList2

####### myArrayN

myArrayN[0] = userListN
myArrayN[1] = emailListN
myArrayN[2] = valueListN
© www.soinside.com 2019 - 2024. All rights reserved.