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

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

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

| improve this answer | |
  • can i add more commands than 3? – k073l Aug 4 '16 at 15:37
  • Yeah, I had a typo in the commands, You should be able to put as many as you want, the index is based off the length of the array. – Zachary Brady Aug 4 '16 at 15:38
  • 2
    If your shuf has the -e option, you can skip the indexing and just do $(shuf -n1 -e "${commands[@]}") – steeldriver Aug 4 '16 at 15:41
  • @steeldriver brilliant. Learn something new every day, updating my answer. – Zachary Brady Aug 4 '16 at 15:42

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.


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

${cmds[RANDOM % ${#cmds[@]}]}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.