shell 在Bash中连接字符串以在For循环中调用数组[duplicate]

eqfvzcg8  于 2023-02-13  发布在  Shell
关注(0)|答案(2)|浏览(97)
    • 此问题在此处已有答案**:

How to iterate over an array using indirect reference?(7个答案)
3天前关闭。
我希望在bash中嵌套几个For循环,首先检查一个数组,然后基于该数组检查第二个数组。

#!/bin/sh

domArr=( "ABC" "DEF" "GHI" )
ABCarr=( "1" "2" "3" )
DEFarr=( "4" "5" "6" )
GHIarr=( "7" "8" "9" )

for domain in "${domArr[@]}"
do
    # This should be 'domain = "ABC"'
    for group in "${domain+arr[@]}"
    do
        # This should be 'group = "1"'
    done
done
zlhcx6iw

zlhcx6iw1#

您可以这样使用它:

domArr=( "ABC" "DEF" "GHI" )
ABCarr=( "1" "2" "3" )
DEFarr=( "4" "5" "6" )
GHIarr=( "7" "8" "9" )

for domain in "${domArr[@]}"
do
    echo "iterating array ${domain}arr ..."
    a="${domain}arr[@]"
    for group in "${!a}"
    do
        echo "$group"
    done
done

输出:

iterating array ABCarr ...
1
2
3
iterating array DEFarr ...
4
5
6
iterating array GHIarr ...
7
8
9
bqjvbblv

bqjvbblv2#

简而言之:

#!/bin/bash

dom=( "ABC" "DEF" "GHI" )
ABC=( "1" "2" "3" )
DEF=( "4" "5" "6" )
GHI=( "7" "8" "9" )

for ((i=0; i<${#dom[@]}; i++)); do
    # This should be 'domain = "ABC"' + "1"
    echo "${dom[i]} ${ABC[i]}"
done
输出
ABC 1
DEF 2
GHI 3

相关问题