gpt4 book ai didi

linux - 在 bash 脚本中运行随机命令

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:46 25 4
gpt4 key购买 nike

我想在 bash 脚本中随机选择一个随机命令。

我试过像

这样的命令

回显 $(( $RANDOM % 12 ))

但它们可以在 UNIX 命令行中工作,但不能在我的 bash 脚本中工作。

有人能解决我的问题吗?

最佳答案

-- 根据评论中的讨论更新答案 --

对于 Bash 用户:

Code given in question works fine. Just don't forget to set permissions to +x (grants executable permission to all). Eg: chmod +x myscript.sh

Caution: Don't set RANDOM to a value. It looses its special properties.

Bash man page says-

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 sub- sequently reset.

对于 dash 用户:

sh in ubuntu is a symbolic link to dash. dash does not support RANDOM variable, it is just another variable.

If you are bound to use sh, you can use date function to generate pseudo randoms only if your script is not time-dependent. (if your script runs at strict intervals of time, it might produce same values)

RANDOM=`date '+%s'`
echo $(( $RANDOM % 12 )) # To generate random numbers less than 12

一般情况:

如果你想生成真正的随机数,使用这个-

dd if=/dev/urandom count=1 2> /dev/null | cksum | cut -f1 -d" "

来源:http://www.linuxquestions.org/questions/programming-9/shell-script-random-variable-4088/

关于linux - 在 bash 脚本中运行随机命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24465591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com