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
.
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.
$_ (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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With