arrays - Bash:一个数组可以保存另一个数组的名称吗?

标签 arrays bash for-loop

我正在编写一个程序并尝试分解存储在数组中的数据,以使其运行得更快。 我正在尝试以这种方式进行:

    data_to_analyze=(1 2 3 4 5 6 7 8 9 10)
    #original array size
    dataSize=(${#data_to_analyze[@]})

    #half of that size
    let samSmall="$dataSize/2"

    #the other half
    let samSmall2=("$dataSize - $samSmall -1")

    #the first half
    smallArray=("${data_to_analyze[@]:0:$samSmall}")

    #the rest
    smallArray2=("${data_to_analyze[@]:$samSmall:$samSmall2}")

    #an array of names(which correspond to arrays)
    combArray=(smallArray smallArray2)
    sizeComb=(${#combArray[@]})

    #for the length of the new array
    for ((i=0; i<= $sizeComb ; i++)); do
        #through first set of data and then loop back around for the second arrays data? 
        for sample_name in ${combArray[i]}; do
            command
            wait
            command
            wait
        done

我想象的是首先只将第一个数据数组提供给 for 循环。当第一个数组完成后,它应该再次通过第二个数组集。

这给我留下了两个问题。 combArray 真的传递了两个较小的数组吗?还有更好的方法吗?

最佳答案

您可以创建一个看起来像数组引用的字符串,然后使用它来间接访问引用数组的元素。它甚至适用于包含空格的元素!

combArray=(smallArray smallArray2)
for array in "${combArray[@]}"
do
    indirect=$array[@]    # make a string that sort of looks like an array reference
    for element in "${!indirect}"
    do
        echo "Element: $element"
    done
done

关于arrays - Bash:一个数组可以保存另一个数组的名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402252/

相关文章:

php - 将关联数组的键数组与整数索引数组进行比较

python - 调整(缩小)ctypes 数组的大小

bash - 在shell中设置进程名称

linux - 时间和时间?灵感来自触摸(1)

javascript - for循环中无法求和

php - 在不更改 PHP 中的数组的情况下获取数组的最后一个元素?

Javascript - 将数组解构为对象

java - 从内部 for 循环中打破外部 while 循环

linux - 日期命令从特定日期返回 30 天

powershell - 对列表使用for循环并将元素设置为环境变量,然后获取值