开发者

Pick and print one of three strings at random in Bash script

How can print a开发者_StackOverflow社区 value, either 1, 2 or 3 (at random). My best guess failed:

#!/bin/bash

1 = "2 million"
2 = "1 million"
3 = "3 million"

print randomint(1,2,3)


To generate random numbers with bash use the $RANDOM internal Bash function:

arr[0]="2 million"
arr[1]="1 million"
arr[2]="3 million"

rand=$[ $RANDOM % 3 ]
echo ${arr[$rand]}

From bash manual for RANDOM:

Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset,it loses its special properties, even if it is subsequently reset.


Coreutils shuf

Present in Coreutils, this function works well if the strings don't contain newlines.

E.g. to pick a letter at random from a, b and c:

printf 'a\nb\nc\n' | shuf -n1

POSIX eval array emulation + RANDOM

Modifying Marty's eval technique to emulate arrays (which are non-POSIX):

a1=a
a2=b
a3=c
eval echo \$$(expr $RANDOM % 3 + 1)

This still leaves the RANDOM non-POSIX.

awk's rand() is a POSIX way to get around that.


64 chars alpha numeric string

randomString32() {
    index=0
    str=""

    for i in {a..z}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {A..Z}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {0..9}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {1..64}; do str="$str${arr[$RANDOM%$index]}"; done

    echo $str
}


~.$ set -- "First Expression" Second "and Last"
~.$ eval echo \$$(expr $RANDOM % 3 + 1)
and Last
~.$ 


Want to corroborate using shuf from coreutils using the nice -n1 -e approach.

Example usage, for a random pick among the values a, b, c:

CHOICE=$(shuf -n1 -e a b c)
echo "choice: $CHOICE"

I looked at the balance for two samples sizes (1000, and 10000):

$ for lol in $(seq 1000); do shuf -n1 -e a b c; done > shufdata
$ less shufdata | sort | uniq -c
    350 a
    316 b
    334 c
$ for lol in $(seq 10000); do shuf -n1 -e a b c; done > shufdata
$ less shufdata | sort | uniq -c
   3315 a
   3377 b
   3308 c

Ref: https://www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜