Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script call a function with a variable?

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! :)

like image 951
Ben Kim Avatar asked Jul 07 '11 08:07

Ben Kim


People also ask

How do you call a function with parameters in shell script?

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.

How do you call a function in shell script?

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.

How do you pass a variable to a function in bash?

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 …

How do you pass a variable from one function to another in shell script?

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.


1 Answers

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
like image 116
e.dan Avatar answered Nov 05 '22 07:11

e.dan