How to set a variable to a random value with bash
Matthew Harrington
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.
4 Answers
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 $RANDOM:
With that simple construct you can easily build powerful scripts using randomness, like in this comic...
6You could use shuf
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 linesExample:
$ 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 How about:
#!/bin/bash
r=$(($RANDOM % 2))
echo $rOr even:
r=$(($(od -An -N1 -i /dev/random) % 2))Or perhaps:
r=$(seq 0 1 | sort -R | head -n 1)Or more hackily:
r=$(($(head -128 /dev/urandom | cksum | cut -c1-10) % 2))And also:
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/urandomAnd turn in into decimal number:
head -c 1 /dev/urandom | od -An -t u1And get the remainder of its division by 2:
echo $((`head -c 1 /dev/urandom | od -An -t u1` % 2)) 0