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
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]}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With