在 Bash 脚本中随机选择并打印三个字符串之一

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5189913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:33:45  来源:igfitidea点击:

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

bashshellrandom

提问by Switchkick

How can print a value, either 1, 2 or 3 (at random). My best guess failed:

如何打印值,1、2 或 3(随机)。我最好的猜测失败了:

#!/bin/bash

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

print randomint(1,2,3)

回答by codaddict

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

要使用 bash 生成随机数,请使用$RANDOM内部 Bash 函数:

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

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

From bash manual for RANDOM:

来自 RANDOM 的 bash 手册:

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.

每次引用此参数时,都会生成 0 到 32767 之间的随机整数。随机数序列可以通过给 RANDOM 赋值来初始化。如果 RANDOM 未设置,它就会失去它的特殊属性,即使它随后被重置。

回答by Lukasz Andersson

64 chars alpha numeric string

64 个字符的字母数字字符串

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
}

回答by Marty McGowan

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