0

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.

1
  • Judging from your previous questions that are all unaccepted... If there is a satisfying answer that solves your problem, take a look at: What should I do when someone answers my question? Note that this will give reputation not only to the answerer but also to you. Commented Jul 14, 2018 at 14:06

3 Answers 3

1

$[...] 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[@]}]}"
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.