Hi I'm creating a shell script.
and an example code looks like
#!/bin/bash
test_func(){
{
echo "It works!"
}
funcion_name = "test_func"
I want to somehow be able to call test_func() using the variable "function_name"
I know that's possible in php using call_user_func($function_name) or by sying $function_name()
is this also possible in the shell scripting?
Huge appreciation for the help! :)
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.
The name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.
To pass any number of arguments to the bash function simply put them right after the function's name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it. The passed parameters are $1 , $2 , $3 …
You have basically two options: Make the variable an environment variable ( export TESTVARIABLE ) before executing the 2nd script. Source the 2nd script, i.e. . test2.sh and it will run in the same shell.
You want the bash built-in eval
. From man bash
:
eval [arg ...]
The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no
args, or only null arguments, eval returns 0.
You can also accomplish it with simple variable substitution, as in
#!/bin/bash
test_func() {
echo "It works!"
}
function_name="test_func"
$function_name
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