I want my bash script to execute random command of given below. For example
[mysterious command] ("command1", "command2", "command3")
I want my bash script to execute random command of given below. For example
[mysterious command] ("command1", "command2", "command3")
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[@]}]}
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
shuf
has the -e
option, you can skip the indexing and just do $(shuf -n1 -e "${commands[@]}")
– steeldriver
Aug 04 '16 at 15:41
rm
saves the day:rm: illegal option -- -
;-) – Kusalananda Aug 04 '16 at 18:57