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.

share|improve this question

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...

Commit Strip - Russian Roulette

share|improve this answer

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
$ 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
share|improve this answer

How about:

#!/bin/bash
r=$(($RANDOM % 2))
echo $r

Or even:

r=$(($(od -An -N1 -i /dev/random) % 2))
share|improve this answer

The easiest way I found was to use shuf -i 0-1 -n 1as it genarates a random number in the range which is inclusive

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.