Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: How do I create function from variable?

Tags:

How do I create a function named from the contents a variable? I want to write a template script that defines a function named after the script’s own file name. Something like this (which of course doesn't work):

#!/bin/bash bname="$(basename $0)" # filename of the script itself  someprefix_${bname}() { # function's name created from $bname variable     echo test } 

So if the script's filename is foo.sh, then it should define a function named someprefix_foo that will echo "test".

like image 475
con-f-use Avatar asked Aug 22 '11 09:08

con-f-use


People also ask

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 I create a function in bash?

Creating a Function in BashThe code between the curly braces {} is the function body and scope. When calling a function, we just use the function name from anywhere in the bash script. The function must be defined before it can be used.

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.

Can you have functions in bash script?

There are two ways to implement Bash functions: Inside a shell script, where the function definition must be before any calls on the function. Alongside other bash alias commands and directly in the terminal as a command.


2 Answers

You can use eval:

eval "someprefix_${bname}() { echo test; }" 

Bash even allows "."s in function names :)

like image 121
Eugene Yarmash Avatar answered Oct 24 '22 21:10

Eugene Yarmash


Indeed, it is instructive that the aforementioned construction derails the possibility of having embedded quotation marks there within and is thus potentially bugulant. However, the following construction does proffer similar functionality whilst not having the constraints of the former answer.

For your review:

source /dev/stdin <<EOF function someprefix_${bname}() {      echo "test"; }; EOF 
like image 38
blake private_last_name Avatar answered Oct 24 '22 20:10

blake private_last_name