简体   繁体   English

在数组中声明并在bash脚本中从数组中随机打印值

[英]declare in array and print the values randomly from array in bash script

Here is my bash script code 这是我的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"


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. 我试图声明数组,然后随机打印数组内的元素大约100次。 Currently the name of the elements are not getting displayed instead it displays as 3 5 8 etc.. Anyhelp will be appreciated. 当前没有显示元素的名称,而是显示为3 5 8,等等。我们将不胜感激。

$[...] 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[@]}]}"

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

This will print a randomized order of your array types . 这将打印您的数组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 : 这些命令使用shuf及其选项:

  • -n , --head-count=COUNT : output at most COUNT lines -n ,-- --head-count=COUNT最多输出COUNT
  • -i , --input-range=LO-HI : treat each number LO through HI as an input line -i ,-- --input-range=LO-HI将每个数字LOHI视为输入行
  • -r , --repeat : output lines can be repeated -r ,-- --repeat输出行可以重复

source man shuf man shuf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM