A
A
artemk1ter2021-02-15 12:42:26
bash
artemk1ter, 2021-02-15 12:42:26

How to randomly select a function and then execute it?

There are three functions:

function1() {
    echo пукпук
}
function2() {
    echo пукпук2
}
function3() {
    echo пукпук3
}


How can you randomly select a feature?

In python, this is done like this:

from random import choice

def func1():
  print("пукпук")

def func2():
  print("пукпук2")	

def func3():
  print("пукпук3")

getrandom = choice([func1, func2, func3])
getrandom()

How to do it in bash?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
X
xibir, 2021-02-15
@artemk1ter

getRandom()
{
   case $(($RANDOM % 3)) in
   0) function1 ;;
   1) function2 ;;
   2) function3 ;;
   esac
}
echo `getRandom`

S
Sergey Sokolov, 2021-02-15
@sergiks

"function$((1 + ($RANDOM % 3)))"
The built-in function in bash $RANDOMwill 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.

Checks
$ ./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)))"

S
Saboteur, 2021-02-15
@saboteur_kiev

eval
eval "function$((RANDOM%3+1))"
or directly
"function$((RANDOM%3+1))"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question