Is it possible to have variable which picks a random number from three pre-decided numbers?
Sample:
var= 10 or 100 or 1000
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIs it possible to have variable which picks a random number from three pre-decided numbers?
Sample:
var= 10 or 100 or 1000
Use an array to hold the values and choose among them using the built-in variable $RANDOM
. For example,
x[0]=10 # One decade
x[1]=100 # One century
x[2]=1000 # One millennium
for ((i=1; i < 20; ++i)); do echo -n " ${x[$RANDOM%3]}"; done; echo
1000 10 10 10 10 100 10 100 100 10 10 100 100 100 10 1000 1000 1000 10
The quality of randomness won't be the best possible (read bytes from /dev/urandom
for that), but it should be more than good enough for a script.
Note 1: As people have observed in the comments, instead of initializing the array elements individually one can of course use an array litteral: x=(10 100 1000)
.
Note 2: Instead of hard-coding the number of elements in the array, a radom element can be extracted by ${x[$RANDOM%${#x[@]}]}
.
x=(10 100 1000)
creates an array from a literal in bash, this would be more readable and more idiomatic
x[0]=10 # This sets the first value of x to ten. Ten is the number of fingers that humans have (excepting birth defects or mutilation). It is also the sum of 9 and 1, or product of 5 and 2. Ten is not prime. A traditional Christmas gift is ten lords a-leaping.
something like that?
If you are using bash (or zsh or ksh93) you can just do:
echo "$((10**($RANDOM%3+1)))"
or
var=$((10**($RANDOM%3+1)))
to assign it to var
You can also use the GNU coreutils shuf
utility:
a=$(shuf -n1 -e 10 100 1000)
Using RANDOM
as per the other answers is almost certainly faster though.
Here's a slightly cryptic way:
printf -v var '1%0*d' $(( RANDOM % 3 + 1 )) 0
This will assign the random value to $var
as required. The printf
format string is 1%0Nd
- this causes 0
to be printed with N
leading zeroes, where N
will be a random integer in the interval [1,3]
.