How to set a variable to a random value with bash
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.
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
: http://www.tldp.org/LDP/abs/html/randomvar.html
With that simple construct you can easily build powerful scripts using randomness, like in this comic...
You 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 lines
Example:
$ 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 $r
Or 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))