Darren Col
Darren Col

Reputation: 129

Using a variable to hold a Bash array name

website_array_$w are w number arrays created by a given argument in command line. I am trying to create a new array temp and store the specific website_array_$w inside it each time. This doesn't seem to work and I get:

temp=${website_array_$w[*]}: bad substitution

What am I doing wrong? After that I want to create a new array random_temp that contains $f random values of array temp.

for ((w=0; w<"$3"; w++)) do
    eval echo 'temp=${website_array_$w[*]}'
    for ((p=0; p<"$4"; p++)) do
         for((i=0; i<"$f"; i++)) do
            eval "random_temp=${temp[$RANDOM % ${#temp[@]}]}"
         done
    done
done

Upvotes: 2

Views: 200

Answers (1)

codeforester
codeforester

Reputation: 42999

Use a nameref (works with Bash versions 4.3 and above):

declare -n temp=website_array_$w || { echo "ERROR: Need bash 4.3 or newer" >&2; exit 1; }

And then use it:

random_temp=${temp[$RANDOM % ${#temp[@]}]}

See:

Upvotes: 1

Related Questions