Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash select random string from list [duplicate]

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

like image 923
Amr Elhosiny Avatar asked Feb 25 '16 09:02

Amr Elhosiny


2 Answers

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]}
like image 59
Benjamin Avatar answered Nov 18 '22 06:11

Benjamin


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.

like image 32
Wolf Avatar answered Nov 18 '22 06:11

Wolf