Skip to content

Instantly share code, notes, and snippets.

@theycallmemac
Created July 21, 2019 07:58
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 theycallmemac/f66b0afeca215df97869dd28612bea74 to your computer and use it in GitHub Desktop.
Save theycallmemac/f66b0afeca215df97869dd28612bea74 to your computer and use it in GitHub Desktop.
A short bash script to simulate a coinflip.
#!/bin/bash
FLIP=$(($(($RANDOM%10))%2))
if [ $FLIP -eq 1 ];then
echo "heads"
else
echo "tails"
fi
@pmarreck
Copy link

pmarreck commented Feb 8, 2022

why do you mod 10 and then take that and mod 2 instead of just modding 2 straight off the bat, as the last bit should be evenly distributed in the set of 0 to 32767 inclusive?

@srozanc-mcs
Copy link

Also to simply the conditional syntax by chaining boolean logic, and removing redundant syntax you can get it pretty clean:

#!/bin/bash
(( RANDOM % 2 )) && echo "heads" || echo "tails"

@pmarreck
Copy link

pmarreck commented Jan 5, 2023

@srozanc-mcs ah, that works because the value returned by (()) is also the return code! (That must also be why the set option to bail on any error may unexpectedly bail on a line that includes (()), depending on the result.)

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