Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created February 9, 2022 23:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmarreck/38b45d1fb7e2e6105fa5226570db8f2d to your computer and use it in GitHub Desktop.
Save pmarreck/38b45d1fb7e2e6105fa5226570db8f2d to your computer and use it in GitHub Desktop.
Simplest way to simulate a coin flip or toss on the Linux command line (in Bash; may work in other shells)
# return code is either 0 (success) or 1 (fail), so you can use it straight-up in logical statements
coinflip() { return $(($RANDOM%2)); }
coinflip && echo "heads" || echo "tails"
@Academie-des-Jeux
Copy link

Academie-des-Jeux commented Aug 13, 2023

You can use the shuf command to do that

info '(coreutils) shuf invocation'
shuf -r -n 1 -e heads tails

@pmarreck
Copy link
Author

True. I guess the advantage of mine is that you can directly use it in conditionals, and it has no external dependencies. Yours possibly also uses a higher quality source of randomness. Thanks for the tip regarding info '(coreutils) shuf invocation', I was only familiar with man primarily!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment