1

I want to create a random seed in a bash script but somehow know how to calculate the same random seed again later on. Suppose I have a range of servers id : 1 to 10. I want to randomly select a server to run a test on. I can do that by using the RANDOM function and see the value

echo $((1 + RANDOM % 10))
6

Then run the test on server id 6.

I do this in a loop for 5 times.

Is there a way to re-calculate the values (ids of servers) later on to see where the tests were ran on ? I should mention I do not wish to store the ids in an array.

Or if there is a way other than using the RANDOM function to accomplish this ?

1 Answer 1

3

Assuming you want re-playable "random" sequence, you could use the command shuf:

$ printf '%s\n' server{1..10} | shuf --random-source file
server3
server6
server5
server9
server1
server2
server4
server8
server7
server10

As long as you use the same file as random source, the sequence will stay the same and could be replayed in the same order.

For info, you can also use the command shuf -e server{1..10} --random-source file if you want to get rid of the printf ... | command.

Use -i option of this shuf command and if you have a consecutive range of number to shuffle.

3
  • 1
    Nice info about --random-source. Use printf '%s\n' server{1..10} to avoid an unnecessary shell loop.
    – Tom Fenech
    Jun 22, 2018 at 9:16
  • 1
    @TomFenech Thanks for the tip!
    – oliv
    Jun 22, 2018 at 9:36
  • 1
    @TomFenech FYI By re-reading the man, I see that shuf -e option can get rid of printf...
    – oliv
    Jun 22, 2018 at 9:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.