Answer the question
In order to leave comments, you need to log in
How to randomly select a function and then execute it?
There are three functions:
function1() {
echo пукпук
}
function2() {
echo пукпук2
}
function3() {
echo пукпук3
}
from random import choice
def func1():
print("пукпук")
def func2():
print("пукпук2")
def func3():
print("пукпук3")
getrandom = choice([func1, func2, func3])
getrandom()
Answer the question
In order to leave comments, you need to log in
getRandom()
{
case $(($RANDOM % 3)) in
0) function1 ;;
1) function2 ;;
2) function3 ;;
esac
}
echo `getRandom`
"function$((1 + ($RANDOM % 3)))"
The built-in function in bash $RANDOM
will return a random 16-bit integer from 0 to 32767 on each call. You can take the remainder of dividing it by 3 - it will be 0, 1 or 2 - and adding one to stick to the word "function" - you get the name of the desired function. It remains to call it - just this line in the bash script, in fact, calls the resulting function.
$ ./rand.sh
пукпук
$ ./rand.sh
пукпук
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук3
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук2
$ ./rand.sh
пукпук
$ cat ./rand.sh
#!/bin/bash
function1() {
echo пукпук
}
function2() {
echo пукпук2
}
function3() {
echo пукпук3
}
"function$((1 + ($RANDOM % 3)))"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question