Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "random" number based on a string in Bash?

I know there are plenty of random number generators out there, but I am looking for something that may be a little more predictable. Is there a way to get a "random" number (one that would be the same in every instance) given a string? I would like to do this in bash. I am looking for something a little more advanced than the count of characters in the string, but not as advanced as a full checksum of it.

The end goal is to get a decimal value, so this could be ran against a string multiple times repeating the result.

like image 256
Kyle Hotchkiss Avatar asked Sep 01 '11 00:09

Kyle Hotchkiss


People also ask

How do I generate a random number in bash?

The random number or a range of random numbers can be generated using the $RANDOM variable. It generates a random number between 0 and 32767 by default. But you can set the range of numbers for generating random numbers by dividing the value of $RANDOM with a specific value.

What is $Random bash?

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. $RANDOM should not be used to generate an encryption key. Example 9-23. Generating random numbers. #!/bin/bash # $RANDOM returns a different random integer at each invocation. #


1 Answers

You need a random number, but you don't want a full checksum, it's contradiction. I think md5sum and sha1sum is really easy to use and should fit your needs:

md5sum <<< "$your_str"

or

sha1sum <<< "$your_str"

Update:

If you need decimal numbers, just:

n=$(md5sum <<< "$your_str")
echo $((0x${n%% *}))
like image 146
Mu Qiao Avatar answered Sep 25 '22 23:09

Mu Qiao