27

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

0

2 Answers 2

63

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

Comments

8

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.