• We had to restore from a backup today after a failed software update. Backup was from 0000 EDT and restored it at 0800 EDT so we lost about 8hrs. Today is 07/20/2024. More info here.

Very simple random number generators in bash

C

CrazedNerd

Guest
Hello everyone, I'm writing this not really as a guide, but thinking out loud...

So you might at one point want a computer to randomly generate a number for you. Maybe you are designing a game of chance, or maybe you and your friends are having trouble making a final decision on something that's not very important. Maybe you need to sacrifice someone to the gods yet be impartial/detached in your decision.

Well, that last part is a joke...but in reality, RNGs are pretty fun. They exist all over the internet, but you can also generate random numbers from the command line line this:

Code:
echo $RANDOM

This one generates a large range of numbers, starting from 0 and ending at 32,767. That's pretty awesome, how many of you have counted to 32,768 ?! Someone certainly has, because it's not that big of number in the grand scheme of things, but it's plenty huge for adding some chance to a lot of different possible things.

You can also use your system's clock (probably like $RANDOM does) to add an element of chance to flow control in a script you write with bash. In the fallowing small example, you use modulus to simulate a coin flip with odd and even numbers from your system clock's seconds:

Code:
now=$(date +%s)

flip=$((now % 2))

if [ $flip = 0 ]; then
        echo HEADS
else
        echo TAILS
fi

The system clock at this point has over a billion seconds, because it has been increasing since the "dawn of unix" on 01/01/1971. Obviously echoing $RANDOM gives you a better selection of options, but unfortunately using $RANDOM in a script results in the first number chosen staying the same number every other time you execute the script, which completely defeats the purpose...but rest assured, there's a lot of predictability in that, because the number of place values won't increase in that number for over 9 years. So, one could make a better RNG using some more complex math than listed above.
 


These may be sufficient for roll the dice games, but neither approach above is cryptographically secure.
 
These may be sufficient for roll the dice games, but neither approach above is cryptographically secure.
Nope, you have to have a more complex algorithm for that, and i have no idea what industry practices are.
 
In reality, random is a spectrum - with a large swath of it being taken up by pseudo random.

Bell's Theorem insists that true random does exist in the universe, but historically we've not been very good with 'random' - especially when we try to observe a chaotic system. It's currently accepted that the decay of a radioactive atom is a random event, which is probably a bit more complicated than you're looking for.

But, there are better sources for randomness that you can use - if you actually wanted to dig into the concept further - better than Linux's randomness even. There's random.org which has a free HTTP API the last time I looked. They claim to be true random and their methodology looks sound to me.

Frankly, I find the philosophy of randomness to be good for late night mental bubblegum. Throughout history, we've considered all sorts of things 'random'. In reality, it's just that we didn't have enough information to make accurate predictions. Things were not random at all.
 
Bell's Theorem insists that true random does exist in the universe, but historically we've not been very good with 'random' - especially when we try to observe a chaotic system. It's currently accepted that the decay of a radioactive atom is a random event, which is probably a bit more complicated than you're looking for.
If that's his theorum, then i disagree. I think that in the universe (nature, the cosmos, etc.) it all boils down to Newtonian cause and effect, people invented god (or in reference to indigenous tribes and the greeks, things that resemble some sort of mysterious entity or collections of them) to try to explain what they don't know...and what people will never know to be completely honest with you. In the universe, i don't think there is random, just mysterious interactions.

To me, random is entirely a mathematical idea or human idea: if i don't know what to expect from the system clock (i can't be counting alongside it without the proper display) then its value is random, and that's what i'm going to be using to try and create an un-sophisticated random number generator. More is coming :)
 
If that's his theorum, then i disagree.

You can disagree, but you're gonna need a whole lot of math and proof. Just 'thinking' it is't enough when it comes to science. I would like to agree with you, but Bell's Theorem has withstood a great deal of scrutiny. Like - a whole lot of scrutiny, testing, repeatable testing, etc...

I'd really like to agree, as it's a bit comforting to think that everything happens when it does because of reasons we can learn. I've examined the proofs and decided that I was glad I'm a mathematician and not a physicist. Wikipedia has an excellent article on the matter.

I actually got to study under Dr. Lorenz (think chaos theory), he was one of the people who wrote my letter of recommendation for grad school. So, yeah, I'd love to think it's just a chaotic system we do not yet fully understand. Then, there's the pesky bit of work done by Bell that turns all that on its head.
 
But, there are better sources for randomness that you can use - if you actually wanted to dig into the concept further - better than Linux's randomness even. There's random.org which has a free HTTP API the last time I looked. They claim to be true random and their methodology looks sound to me.
Their logic here is sound in my opinion as well:


but the reference the RNG is using in their "truly random number" generator is chaos, not randomness. What they are theorizing of doing is generating rapid successions of activity (like the instability of atomic particles) so that it generates possibilities too fast for humans to predict.

You can disagree, but you're gonna need a whole lot of math and proof.

Yes, in math you can't make your postulates without proof to back it up, and in that sense it's a perfect system that can be used to estimate (or say for certain, based on if a mathematician has enough evidence to work with) distances of stars, and predict when the sun will stop working in the way we need it to in order to survive as a species. I think all the current predictions of when the sun will kill mammalian life are just estimations though, a lot of folks in academic science believe that it will happen before it becomes a red giant, and i do see the power of empirical science...so on faith alone, i believe they are right.

However, i still don't agree that there are "truly random things" in the universe just because i know that if i put water inside of a loaf of bread and let it sit outside in the summer, it will get moldy very fast. That's just as certain as the fact that i'm going to die. People came up with different theories that would seem wierd to us as to why those things happen before someone was able to repeat them in controlled conditions.

You can have truly random numbers just because math is an artificial system, but to me naturally random denies the chain of cause-and-effect. Whatever bell said about his theory came from a system of reasoning created by him. Time isn't real either.

HOWEVER, this is where i feel spooked out thinking about all of this: does it really make any sense to say that our universe BEGAN at a certain point in time? Maybe it was always just here? According to aristotlian logic, that doesn't really make any sense but how could anyone possibly doubt the claim that our universe was always here using evidence?
 
However, i still don't agree that there are "truly random things" in the universe just because i know that if i put water inside of a loaf of bread and let it sit outside in the summer, it will get moldy very fast.

I suppose, but I don't know if anyone's gonna take you seriously - without a buttload of evidence, or something that explains the observed results better *and* makes better predictions. I'll root for you! You can make it your mission in life to disprove 'em. I'll definitely root for you, as I don't really like the concept of true random.

HOWEVER, this is where i feel spooked out thinking about all of this: does it really make any sense to say that our universe BEGAN at a certain point in time?

It doesn't really have to 'make sense'. If we reverse what we observe, the universe was smaller and smaller. So, with that line of thinking, at some point the universe either didn't exist or it was REALLY small. If we then accept some basic understanding - things like matter and energy being finite, as neither are created nor destroyed, we end up concluding a 'big bang' must have happened, or something quite similar - though there was no noise or anything they say. That's pretty Newtonian. I don't think I have the capacity to disprove it and I am a fan of the scientific method.

There's more to respond to, but this is a pretty low-effort response. I've got a football game to watch and someone showing up shortly. But, if you want to dismantle the consensus of true random, you will want to start with Bell's theorem. You'll have your work cut out for you.
 
I suppose, but I don't know if anyone's gonna take you seriously - without a buttload of evidence, or something that explains the observed results better *and* makes better predictions. I'll root for you! You can make it your mission in life to disprove 'em. I'll definitely root for you, as I don't really like the concept of true random.



It doesn't really have to 'make sense'. If we reverse what we observe, the universe was smaller and smaller. So, with that line of thinking, at some point the universe either didn't exist or it was REALLY small. If we then accept some basic understanding - things like matter and energy being finite, as neither are created nor destroyed, we end up concluding a 'big bang' must have happened, or something quite similar - though there was no noise or anything they say. That's pretty Newtonian. I don't think I have the capacity to disprove it and I am a fan of the scientific method.

There's more to respond to, but this is a pretty low-effort response. I've got a football game to watch and someone showing up shortly. But, if you want to dismantle the consensus of true random, you will want to start with Bell's theorem. You'll have your work cut out for you.
I personally don't need those assertions proven just to know that it's just a human thing like time, or maybe there are other creatures who go crazy with abstractions like we do...and mathematically, i've read it's likely there are other "intelligent life forms" out there, so it being a "human thing" is just me saying that random numbers are abstract in a way that's convenient for me.

And i appreciate someone who's actually knowledgeable about academic math/physics explain to me why it's the consensus that there was a "big bang". I've basically said exactly what i've said to you and people just parrot my theory like "Yep, it's possible that it has always just been here!". I tend to relish in thinking about "the universe", and i would probably have been better off if i had my shit together when i was younger so that i could have become an astronomer...

...but that's all just personal speculation. What's crazy to think about is how many universes may have existed before this one, or if futurama is right in theorizing that maybe this one universe just repeats itself over and over again!
 
So I finally found a way to do what i did in the OP with a little more randomness/variety, yet I'm still kinda disappointed that there aren't many other options in terms of generating random numbers in bash alone. For someone looking for something more in-depth/professional, there are lot's of APIs out there, but it can be fun to re-invent the wheel in your own way.

The script i'm going to post here is not an algorithm for generating random numbers, but semi-random websites instead. I got the idea from this:


I don't have any idea how they generating random websites, but it's inspiring and interesting because so much of the internet now adays is just based on the "you" algorithm, which can get boring after a while.

In my script, what i've done is expanded the coin flip idea to have 10 possibilities instead of two. I've done that by extracting the system clock's final second (which keeps changing):

Code:
digit=$(echo $now | sed 's/\([0-9]\{3\}\)\([0-9]\{3\}\)\([0-9]\{3\}\)\([0-9]\)/\4/g')

This is then fed into 10 if/else possibilities. However, I decided that wasn't random enough because you can always expect the implicit number to get higher. So in order to counter that, i also nested it in the odd/even coin flip scheme and created a reversal of the numerical value of possibilities:

Code:
now=$(date +%s)

oddeven=$((now % 2))

digit=$(echo $now | sed 's/\([0-9]\{3\}\)\([0-9]\{3\}\)\([0-9]\{3\}\)\([0-9]\)/\4/g')

if [ $oddeven = 0 ];then
        if [ "$digit" = 0 ]; then
                firefox https://theuselessweb.com/ &> /dev/null &
        elif [ "$digit" = 1 ]; then
                firefox https://rateyourmusic.com/ &> /dev/null &
        elif [ "$digit" = 2 ]; then
                firefox https://surrealismtoday.com/blog/ &> /dev/null &
        elif [ "$digit" = 3 ]; then
                firefox https://apnews.com/ &> /dev/null &
        elif [ "$digit" = 4 ]; then
                echo "Slot for site 5"
        elif [ "$digit" = 5 ]; then
                echo "Slot for site 6"
        elif [ "$digit" = 6 ]; then
                echo "Slot for site 7"
        elif [ "$digit" = 7 ]; then
                echo "Slot for site 8"
        elif [ "$digit" = 8 ]; then
                echo "Slot for site 9"
        else
                echo "Slot for site 10"
        fi
else
        if [ "$digit" = 9 ]; then
                firefox https://theuselessweb.com/ &> /dev/null &
        elif [ "$digit" = 8 ]; then
                firefox https://rateyourmusic.com/ &> /dev/null &
        elif [ "$digit" = 7 ]; then
                firefox https://surrealismtoday.com/blog/ &> /dev/null &
        elif [ "$digit" = 6 ]; then
                firefox https://apnews.com/ &> /dev/null &
        elif [ "$digit" = 5 ]; then
                echo "Slot for site 5"
        elif [ "$digit" = 4 ]; then
                echo "Slot for site 6"
        elif [ "$digit" = 3 ]; then
                echo "Slot for site 7"
        elif [ "$digit" = 2 ]; then
                echo "Slot for site 8"
        elif [ "$digit" = 1 ]; then
                echo "Slot for site 9"
        else
                echo "Slot for site 10"
        fi
fi

To re-iterate, the odd-even scheme for the system clock value works because there's an even distribution of odd and even numbers numbers in 0 through 9.

Even numbers: 0, 2, 4, 6, 8

Odd numbers: 1, 3, 5, 7, 9

So there's the same possibility that the next second will correspond with either an even or odd number...

Anyways, I had trouble coming up with 10 websites that i actually thought were cool, so there's that. Half of the internet is basically porn anyway, and i don't have much interest in porn.

What a worthless invention! Of course anyone is free to use it as they please.
 
I have seen many misstatements of fact and unsubstantiated assertions from @CrazedNerd in this thread (and sadly, elsewhere). @KGIII has done his best to explain the flaws in those statements. I support and commend KGIII's effort, however fruitless. There is so much here that I do not know where to start and will not engage.

"Argue with no true believers." (Phyllis McGinley)
 
I have seen many misstatements of fact and unsubstantiated assertions from @CrazedNerd in this thread (and sadly, elsewhere). @KGIII has done his best to explain the flaws in those statements. I support and commend KGIII's effort, however fruitless. There is so much here that I do not know where to start and will not engage.

"Argue with no true believers." (Phyllis McGinley)
Dude, you never explain yourself ever. Stop trolling. This was never meant to be some sort industry based random number generator. Please stop pointing fingers at other people.
 
Dude, you never explain yourself ever. Stop trolling. This was never meant to be some sort industry based random number generator. Please stop pointing fingers at other people.
It is clear to anyone with training and experience that you do not have a full and complete understanding of this discipline. There is no purpose to "explain myself". @KGIII already tried to explain the issues to you and he addressed the specific points that you made.

The purpose of my recent post was to make it clear to others that @KGIII is correct and your arguments have flaws. My comments stand on their own. I am not trolling anyone, but I will not engage with you in a debate that I cannot win, nor will I provide you with more fodder to make further erroneous, misleading statements.

-> I trust the judgement of others who read this thread to determine for themselves what is true.

(I truly hope that this is my final post in this thread.)
 
Last edited:
(I truly hope that this is my final post in this thread.)

I hope so, too. Only you can make that happen.

Wizard
 
I just watched this you tube video about how RNGs work from the more professional perspective that so many people year for, and found it interesting:


So in addition to inputting data from radioactive particles, you also can create un-predictable scenarios from changes in air-pressure. That probably isn't as chaotic as the sub-atomic activity generated by heavy metals, but I imagine it's less expensive. Also, these poker shufflers described in the video don't stop shuffling themselves until the cards are actually dealt, something impossible to achieve with human dealers without weird cybernetic enhancements...
 
A quick and dirty hack.

strings /dev/random | head -n1

But usually these strings will be fairly short.

Another hack if you have "pwgen" installed ( password generator )

pwgen 10 1

The 10 is the string length. The 1 is how many strings you want listed.
 
A quick and dirty hack.

strings /dev/random | head -n1

But usually these strings will be fairly short.

Another hack if you have "pwgen" installed ( password generator )

pwgen 10 1

The 10 is the string length. The 1 is how many strings you want listed.
Nice, someone already built something into Ubuntu to randomly generate strings, not surprising at all considering that linux distros tend to be designed for developers...

That's definitely random enough for something "quick and dirty":
Code:
for i in {1..20}; do strings /dev/random | head -n1; done
sV!.\
?$,!
`JfwE
1VEx
gys:
sg/:z,
5\aYEN
J0vw
m[2-
v/|)u
`yoT
;|=fO
soZV
$:\_
}[Z7
[!Mu0
lf80
2&M,
pS)^
=5qN
 
And i appreciate someone who's actually knowledgeable about academic math/physics explain to me why it's the consensus that there was a "big bang". I've basically said exactly what i've said to you and people just parrot my theory like "Yep, it's possible that it has always just been here!".

Oh, it's definitely possible that it *could* have always been here - but all the evidence and observation we have is best answered by there being a 'big bang' (or a specific period of time where the universe began rapidly expanding). The universe could also be here because we're the imagination of a purple gorilla.

At this moment in time, the big bang is the best model we have for making predictions about the universe's behavior. So, we use that model. If something better comes along, we'll use that. Right now, we use this model because observation matches the prediction.

Edit: We shouldn't wander too far off topic. I'd say we should have a science thread somewhere in off topic, but I'm not sure how much attention folks'd pay.
 
Edit: We shouldn't wander too far off topic. I'd say we should have a science thread somewhere in off topic, but I'm not sure how much attention folks'd pay.
You know, i'm actually surprised this thread is only a page long because of the amount of topics we have lightly discussed here:

bash PRNGs --> cyrptography --> complexity of industry need --> mathmatical randomness --> CrazedNerd disagrees --> KGIII disagrees --> CrazedNerd disagrees and ooh shiny stuff --> CrazedNerd is a fool and i commend KGIII --> i know you are, but what am i, troll! --> CrazedNerd is not credible, hopefully i can stop posting in CrazedNerd's thread --> "good luck!" -WIzard --> we are going to die --> ooh a poker RNG --> RSGs in bash --> oooh cool --> we are off topic

So basiclaly humans, if we are humans (i have genuinely questioned that in reference to myself before...), add a level of randomness to any topic, so maybe somebody could use random strings from news articles, mix them with math, then that could be close to truly random. However, i keep hearing about how AIs are becoming writers...so there's another element of randomness and predictability.
 

Members online


Top