In a program, I need to set a variable to a random value of either 0 or 1.
I can't figure out how to do it and Google has failed me.
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
One easy method is to use
$RANDOM to retrieve a pseudorandom 16 bit integer number in the range [0; 32767]. You can simply convert that to [0; 1] by calculating modulo 2 of the random number:
echo $(( $RANDOM % 2 ))
More information about Bash's
With that simple construct you can easily build powerful scripts using randomness, like in this comic...
You could use
DESCRIPTION Write a random permutation of the input lines to standard output. -i, --input-range=LO-HI treat each number LO through HI as an input line -n, --head-count=COUNT output at most COUNT lines
$ foo=$(shuf -i0-1 -n1) $ echo $foo 1 $ foo=$(shuf -i0-1 -n1) $ echo $foo 0 $ foo=$(shuf -i0-1 -n1) $ echo $foo 0 $ foo=$(shuf -i0-1 -n1) $ echo $foo 1
#!/bin/bash r=$(($RANDOM % 2)) echo $r
r=$(($(od -An -N1 -i /dev/random) % 2))
r=$(seq 0 1 | sort -R | head -n 1)
Or more hackily:
r=$(($(head -128 /dev/urandom | cksum | cut -c1-10) % 2))
r=$(apg -a 1 -M n -n 1 -m 8 -E 23456789 | cut -c1)
As well as:
r=$((0x$(cut -c1-1 /proc/sys/kernel/random/uuid) % 2))
This script has no benefits over existing answers. Just for entertainment purposes...
Get one byte from
/dev/urandom (although in general sending arbitrary binary characters to console is not recommended™ because it might give unexpected/confusing results):
head -c 1 /dev/urandom
And turn in into decimal number:
head -c 1 /dev/urandom | od -An -t u1
And get the remainder of its division by 2:
echo $((`head -c 1 /dev/urandom | od -An -t u1` % 2))