Bash select random string from list [duplicate]

江枫思渺然 提交于 2020-08-02 07:31:03

问题


I have a list of strings that I want to select one of them at random each time I launch the script.

For example

SDF_BCH_CB="file1.sdf"
SDF_BCH_CW="file2.sdf"
SDF_BCH_RCB="file3.sdf"
SDF_BCH_RCW="file4.sdf"
SDF_TT="file5.sdf"

Then I want to be randomly select from the above list to assign the following two variables.

SDFFILE_MIN=$SDF_BCH_CW
SDFFILE_MAX=$SDF_TT

How can I do this ?

Thanks


回答1:


Store in array, count and random select:

#!/bin/bash
array[0]="file1.sdf"
array[1]="file2.sdf"
array[2]="file3.sdf"
array[3]="file4.sdf"

size=${#array[@]}
index=$(($RANDOM % $size))
echo ${array[$index]}



回答2:


Use the built in $RANDOM function and arrays.

DF_BCH_CB="file1.sdf"
SDF_BCH_CW="file2.sdf"
SDF_BCH_RCB="file3.sdf"
SDF_BCH_RCW="file4.sdf"
SDF_TT="file5.sdf"

ARRAY=($DF_BCH_CB $SDF_BCH_CW $SDF_BCH_RCB $SDF_BCH_RCW $SDF_TT)
INDEX=(0 1 2 3 4)
N1=$((RANDOM % 5))
SDFFILE_MIN=${ARRAY[$N1]}
N2=$((RANDOM % 4))
if [ "$N2" = "$N1" ] ; then
    N2=$N1+1
fi
SDFFILE_MAX=${ARRAY[$N2]}

echo $SDFFILE_MIN
echo $SDFFILE_MAX

This gets two different strings for SDFFILE_MIN and SDFFILE_MAX. If they don't have to be different, remove the if statement in the middle.



来源:https://stackoverflow.com/questions/35623462/bash-select-random-string-from-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!