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".
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 …
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.
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.
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.
You can use eval
:
eval "someprefix_${bname}() { echo test; }"
Bash even allows "."
s in function names :)
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
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