4

I want my bash script to execute random command of given below. For example

[mysterious command] ("command1", "command2", "command3")

2 Answers2

12

Put your commands in an array.

cmds=( "cmd1" "cmd2" "cmd3" )

$RANDOM is a random number and ${#cmds[@]} evaluates to the length of your array (3 in this example). $(( RANDOM % ${#cmds[@]} )) will be a random number between 0 and one less than the length of the array cmds, i.e. 0, 1, or 2.

i=$(( RANDOM % ${#cmds[@]} ))

Doing the following would pick the string out of $cmds corresponding to the index $i and execute it as a command.

${cmds[i]}

or all in one go (which looks a bit horrible):

${cmds[RANDOM % ${#cmds[@]}]}
Kusalananda
  • 333,661
3

This should accomplish what you're looking for.

COMMANDS=("command1" "command2" "command3")
$(shuf -n1 -e "${COMMANDS[@]}")

Takes the array and uses shuf to generate a random command.

UPDATE: Changed shuf command per @steeldriver