10

I have a file which contains entries numbered 0 to 149. I am writing a bash script which randomly selects 15 out of these 150 entries and create another file from them.
I tried using random number generator:

var=$RANDOM
var=$[ $var % 150 ]

Using var I picked those 15 entries. But I want all of these entries to be different. Sometimes same entry is getting picked up twice. Is there a way to create a sequence of random numbers within a certain range, (in my example, 0-149) ?

1 Answer 1

21

Use shuf -i to generate a random list of numbers.

$ entries=($(shuf -i 0-149 -n 15))
$ echo "${entries[@]}"
55 96 80 109 46 58 135 29 64 97 93 26 28 116 0

If you want them in order then add sort -n to the mix.

$ entries=($(shuf -i 0-149 -n 15 | sort -n))
$ echo "${entries[@]}"
12 22 45 49 54 66 78 79 83 93 118 119 124 140 147

To loop over the values, do:

for entry in "${entries[@]}"; do
    echo "$entry"
done
Sign up to request clarification or add additional context in comments.

4 Comments

What does the [@] mean in ${entries[@]? Say I wanted to run a loop on these values , can i do : for i in $entries do ... done ?
OSX users: installable via Homebrew: brew install coreutils; invoke as gshuf.
@user3286661 [@] expands to 'all items in array' - if you do 'echo $entries' you will get the first item. If you do 'echo ${entries[@]}' it will echo all items.
I can't get it to provide any more than 1001 numbers. CentOS 64 bit. Is that expected?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.