raptor0102
raptor0102

Reputation: 309

bad substitution shell- trying to use variable as name of array

#!/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

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!

Upvotes: 2

Views: 3066

Answers (1)

chepner
chepner

Reputation: 532508

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

Upvotes: 2

Related Questions