Ask Dave Taylor
  • Facebook
  • Instagram
  • Linkedin
  • Pinterest
  • Twitter
  • YouTube
  • Home
  • YouTube Videos
  • Top Categories
  • Subscribe via Email
  • Ask A Question
  • Meet Dave
  • Home
  • Linux Shell Script Programming
  • How Can I Work with Random Numbers in the Linux Shell?

How Can I Work with Random Numbers in the Linux Shell?

December 5, 2019 / Dave Taylor / Linux Shell Script Programming / No Comments

For a programming project, I’m supposed to demonstrate different ways that randomization can be utilized within a Linux shell script. Can you help get me started, please?

Randomization and random numbers are both quite fascinating and rather obscure topics from a mathematical perspective. Turns out that it’s pretty dang hard to truly produce random numbers, though you wouldn’t think so. Heck, just think of a deck of playing cards: How many times do you need to shuffle it to truly randomize the cards? [actually, that’s a function of how many cards are in the deck and the answer is seven for a standard deck of 52 cards. Seven good shuffles and your deck will be optimally randomized, as explained in painful mathematical detail in this article. Now you know.]

I also generally have a practice of not helping students out with homework, but I let your question “age” for a few weeks so either you’ve figured it out and turned in your assignment or you’re now running late. 🙂

In any case, like all operating systems, Linux has a fair amount of code within the system to aid in generating sequences of random numbers. They’re important for all sorts of reasons, but you can access them easily enough. The standard way from the command line is the rand command, but let’s do that Linux thing and see what comes up with a search:

$ man -k random | grep '(1'
apg (1) - generates several random passwords
openssl-rand (1ssl) - generate pseudo-random bytes
rand (1ssl) - generate pseudo-random bytes
shuf (1) - generate random permutations
$

You can see that there are four user level commands (section 1 of the man pages, which is why I used that as the grep pattern). Of these rand is the most important and easiest to work with:

$ rand
5709
$ rand
5654

Turns out you can accomplish exactly the same with the special Bash shell variable RANDOM too:

$ echo $RANDOM
23918
$ echo $RANDOM
25248
$ echo $RANDOM
15456

This isn’t present in every shell, however, so using the rand function is more portable. Want to choose between two possible outcomes, or have a 50% chance that you’ll pick a given option? Here’s some basic code:

if [ $(( $(rand) % 2 )) -eq 1 ]    # 50% chance
then
echo it happened
else
echo it did not happen
fi

How about a 25% chance? Just change the conditional expression to $(rand) % 4 and look for a single value. 10% chance? $(rand) % 10 and look for a single value. It really is that easy.

It’s interesting is to tap one of the other randomized command line utilities while we’re talking about random and randomization. For example, the random password generator apg is handy:

$ apg
=Ovitweb4 (EQUAL_SIGN-Ov-it-web-FOUR)
Loyk~On2owtyo (Loyk-TILDE-On-TWO-owt-yo)
^okDyufJuksh4 (CIRCUMFLEX-ok-Dyuf-Juksh-FOUR)
fi!froxVium0 (fi-EXCLAMATION_POINT-frox-Vi-um-ZERO)
omm:Ledeben1 (omm-COLON-Led-eb-en-ONE)
=oz3DretAparv (EQUAL_SIGN-oz-THREE-Dret-Ap-arv)

I have no idea why the default is to offer a pronounceable version of each password, but you can disable that with the -a 1 flag, like so:

$ apg -a 1
bk,1Q6g7
}k^j?&mS{
:Eu]:'5A~
E$/HikQAV
gJg/&t["#I
TdBNLH}/X>

Finally, the shuf command is potentially useful in a script too as you can feed it lines of text and it’ll “shuffle” them and then output the contents as a randomized sequence of lines. For example:

$ cat cards
ace of spades
two of spades
three of spades
four of spades
five of spades
six of spades
$ shuf cards
two of spades
three of spades
six of spades
ace of spades
four of spades
five of spades
$ shuf cards
ace of spades
three of spades
two of spades
five of spades
four of spades
six of spades

There’s lots more you can do with random numbers in the Linux shell, but that’ll definitely get you started. And if you haven’t yet started, well, good luck with your assignment.

Pro Tip: I’ve been writing about Linux scripting for years. I even wrote a book about it! Please check out my Linux help library for lots more tutorials!

About the Author: Dave Taylor has been involved with the online world since the early days of the Internet. Author of over 20 technical books, he runs the popular AskDaveTaylor.com tech help site. You can also find his gadget reviews on YouTube and chat with him on Twitter as @DaveTaylor.

Let’s Stay In Touch!

Never miss a single article, review or tutorial here on AskDaveTaylor, sign up for my fun weekly newsletter!
Name: 
Your email address:*
Please enter all required fields
Correct invalid entries
No spam, ever. Promise. Powered by FeedBlitz
Please choose a color:
Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you, Dave, for all your helpful information by buying you a cup of coffee!
apg, card shuffling, linux random numbers, linux shell script, rand, random, random numbers, random numbers script, randomization, shell script, shell script random, shuf

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

Recent Posts

  • How to Enlarge Font Size in Apple’s Books App on the iPad
  • Chromebook Owner’s Guide to Antivirus & Anti-Malware Solutions
  • Everything You Need to Know about Apple’s Clean Energy Charging
  • How Can I Watch Free Classic Movies on my Windows PC?
  • How Can I Maximize Online Privacy with a VPN Connection?

On Our YouTube Channel

TWT Audio REVO TW310 Budget Headset -- DEMO & REVIEW

iClever Bluetooth 34-Key Number Pad Keyboard -- REVIEW

Categories

  • AdSense, AdWords, and PPC Help (106)
  • Amazon, eBay, and Online Shopping Help (164)
  • Android Help (228)
  • Apple iPad Help (148)
  • Apple Watch Help (53)
  • Articles, Tutorials, and Reviews (346)
  • Auto Tech Help (17)
  • Business Advice (200)
  • ChromeOS Help (34)
  • Computer & Internet Basics (782)
  • d) None of the Above (166)
  • Facebook Help (384)
  • Google, Chrome & Gmail Help (188)
  • HTML & Web Page Design (247)
  • Instagram Help (49)
  • iPhone & iOS Help (625)
  • iPod & MP3 Player Help (173)
  • Kindle & Nook Help (99)
  • LinkedIn Help (88)
  • Linux Help (174)
  • Linux Shell Script Programming (90)
  • Mac & MacOS Help (914)
  • Most Popular (16)
  • Outlook & Office 365 Help (33)
  • PayPal Help (68)
  • Pinterest Help (54)
  • Reddit Help (19)
  • SEO & Marketing (82)
  • Spam, Scams & Security (96)
  • Trade Show News & Updates (23)
  • Twitter Help (222)
  • Video Game Tips (66)
  • Web Site Traffic Tips (62)
  • Windows PC Help (951)
  • Wordpress Help (206)
  • Writing and Publishing (72)
  • YouTube Help (47)
  • YouTube Video Reviews (159)
  • Zoom, Skype & Video Chat Help (62)

Archives

Social Connections:

Ask Dave Taylor


Follow Me on Pinterest
Follow me on Twitter
Follow me on LinkedIn
Follow me on Instagram


AskDaveTaylor on Facebook



microsoft insider mvp


This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this site or on any linked site. Further, please note that by submitting a question or comment you're agreeing to our terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site. Our lawyer says "Thanks for your cooperation."
© 2023 by Dave Taylor. "Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.
Privacy Policy - Terms and Conditions - Accessibility Policy