user3906723
user3906723

Reputation: 145

declare in array and print the values randomly from array in bash script

Here is my bash script code

declare -a types=("m4.xlarge" "m5.12xlarge" "m5d.12xlarge" "m4.large" "m4.16xlarge" "t2.2xlarge" "c4.large" "c5.xlarge" "r4.2xlarge" "x1e.4xlarge" "h1.16xlarge" "i3.16xlarge" );
echo "array declared"


for i in {1..100}
do

for (( i=1; i<${arraylength}+1; i++ ))   
 do

#index=$( jot -r 1  0 $((${#expressions[@]} - 1)) )
    randominstancetype=$[$RANDOM % ${#types[@]}];

    #randominstancetype=$( shuf -i0-1 -n1 $((${#types[@]} )) );
    #randominstancepvtiptype=$[$RANDOM % ${#pvtip[@]}];
        #randominstancepubiptype=$[$RANDOM % ${#pubip[@]}];
done
 done

I am trying to declare array and then print the elements inside the array randomly for around 100 times. Currently the name of the elements are not getting displayed instead it displays as 3 5 8 etc.. Anyhelp will be appreciated.

Upvotes: 0

Views: 1141

Answers (3)

kvantour
kvantour

Reputation: 26581

This will print a randomized order of your array types.

for j in {1..100}; do
  for i in $(shuf -i 0-$((${#types[*]}-1))); do
     printf "%s " "${types[i]}";
  done;
  printf "\n";
done

If you would allow repetitions, then you can do

for j in {1..100}; do
  for i in $(shuf -n ${#types[*]} -r -i 0-$((${#types[*]}-1))); do
     printf "%s " "${types[i]}";
  done;
  printf "\n";
done

The commands make use of shuf and its options :

  • -n, --head-count=COUNT: output at most COUNT lines
  • -i, --input-range=LO-HI: treat each number LO through HI as an input line
  • -r, --repeat: output lines can be repeated

source man shuf

Upvotes: 0

hnicke
hnicke

Reputation: 602

Try this snippet:

#!/bin/bash  
declare -a types=("m4.xlarge" "m5.12xlarge" "m5d.12xlarge" "m4.large" "m4.16xlarge" "t2.2xlarge" "c4.large" "c5.xlarge" "r4.2xlarge" "x1e.4xlarge" "h1.16xlarge" "i3.16xlarge" )
echo "array declared"

max_random=32767
type_count=${#types[@]}
factor=$(( max_random / type_count ))

for i in {1..1000}
do
    random_index=$(( $RANDOM / $factor ))
    random_instance_type=${types[$random_index]}
    echo $random_instance_type
done

Upvotes: 0

PesaThe
PesaThe

Reputation: 7519

$[...] is the old and deprecated version of $((...)). So what you are doing is just simple arithmetic expansion that expands back to the random index.

To access an element of the array with the generated index, use:

echo "${types[$RANDOM%${#types[@]}]}"

Upvotes: 1

Related Questions