简体   繁体   中英

Run random command in bash script

I would like to randomly select one random command in a bash script.

I have tried commands like

echo $(( $RANDOM % 12 ))

But they work in the UNIX command line but not in my bash script.

Anyone have a solution for my problem?

-- Updated answer as per discussion in comments --

For Bash Users:

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.

For dash Users:

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 

In General:

If you want to generate true random numbers use this-

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

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

Create the shell script test.sh

chmod +x test.sh

content of test.sh

#!/bin/bash
echo $(( $RANDOM % 12 ))

Run it via

bash test.sh

or

./test.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM