错误的替换Shell-尝试使用变量作为数组的名称 [英] bad substitution shell- trying to use variable as name of array

查看:84
本文介绍了错误的替换Shell-尝试使用变量作为数组的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/bash
array=( 2 4 5 8 15 )
a_2=( 2 4 8 10 )
a_4=( 2 4 8 10 )
a_5=( 10 12 )
a_8=( 8 12 )
a_15=( 2 4 )
numberOfTests=5
while [ $i -lt ${#array[@]} ]; do
    j=0
    currentArray =${array[$i]}
    *while [ $j -lt ${#a_$currentArray [@]} ]; do #### this line i get ->>>> bad substitution*
        ./test1.sh  "${array[$i]}" -c "${a_"$currentArray "[$j]}" &
        let j=j+1
    done
    let i=i+1
done

所以我尝试这段代码,在一个数组(称为数组)上循环,该数组应该指出我们现在循环的数组号(a_X).并每次指出当前的位置和价值.有人可以帮助我如何使用$ currentArray正常工作,以便我知道数组的长度和值吗?我进入我标记为错误的行.谢谢你们!

so Im trying this code, loop over an array(called array), The array should point out the array number we are now looping(a_X). And every time to point out the current place and value. can anybody help me how im using the $currentArray to work properly so I can know the length of the array and the value? I get in the line I marked an error. Thank you guys!

推荐答案

最简单的解决方案是在 array 中存储数组的全名,而不仅仅是数字后缀.然后,您可以在直接遍历数组的值而不是索引的同时使用间接参数扩展.

The simplest solution is to store the full names of the arrays, not just the numerical suffix, in array. Then you can use indirect parameter expansion while iterating directly over the values, not the indices, of the arrays.

# Omitting numberOfTests has it does not seem to be used
array=(a_2 a_4 a_5 a_8 a_15)
a_2=( 2 4 8 10 )
a_4=( 2 4 8 10 )
a_5=( 10 12 )
a_8=( 8 12 )
a_15=( 2 4 )
for arr in "${array[@]}"; do
    currentArray=$arr[@]
    for value in "${!currentArray}"; do
        ./test1.h "${arr#a_}" -c "$value" &
    done
done

这篇关于错误的替换Shell-尝试使用变量作为数组的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆