Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke function whose name is stored in a variable in bash

Let's say I have:

function x {     echo "x" } call_func="x" 

Now, I can simply use eval as follows:

eval $call_func 

but I was wondering if there was some other way of invoking the function (if it exists) whose name is stored in the variable: call_func.

like image 397
hjpotter92 Avatar asked Oct 28 '15 09:10

hjpotter92


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

How do you call a specific function in bash?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

Can bash function access global variable?

Global variablesThey are visible and valid anywhere in the bash script. You can even get its value from inside the function. If you declare a global variable within a function, you can get its value from outside the function.


1 Answers

You should be able to just call the function directly using

$call_func 

For everything else check out that answer: https://stackoverflow.com/a/17529221/3236102 It's not directly what you need, but it shows a lot of different ways of how to call commands / functions.

Letting the user execute any arbitrary code is bad practice though, since it can be quite dangerous. What would be better is to do it like this:

if [ $userinput == "command" ];then     command fi 

This way, the user can only execute the commands that you want them to and can even output an error message if the input was incorrect.

like image 61
Dakkaron Avatar answered Oct 03 '22 09:10

Dakkaron