Hi all,
Does anyone know if it possible to append a parameter to a function name?
Something like the following:
function tnsrec_${SERVICE_NAME} {
code..
}
Any ideas?
Hi all,
Does anyone know if it possible to append a parameter to a function name?
Something like the following:
function tnsrec_${SERVICE_NAME} {
code..
}
Any ideas?
Are you trying to achieve something like this?
# cat test.sh
function tnsrec_SERVICE1 {
echo "Test ok"
}[
SERVICE_NAME=SERVICE1
eval tnsrec_${SERVICE_NAME}
# ./test.sh
Test ok
hmm, thnx for feedback.
I am supplying a parameter to a script and need to use that parameter to name a function.
In your code, where is the close ']' bracket?
also, when do I place the eval ?
Thanks again.
jd
You can't use eval to dynamically name a function in that way.
But why would you want to?
If you can pass any value into a script and thus have a function with any name, why not just chose any name for the function to begin with?
What you are trying to do doesn't really make any sense.
BTW, I think the [ may have been a typo.
I need to dynamically name a fnction so a watchdog script can identify a process.
so I need to append a parameter to a function name.
If you have any idea on how to do this I would be grateful.
$ cat myScript
F=${1:-default}
. <(cat <<!
function somefunction_$F {
echo "\$0: Test OK"
}
!)
eval somefunction_$F
# ./myScript blah
somefunction_blah: Test OK
# ./myScript
somefunction_default: Test OK
This method might be a bit inflexible since you have to escape anything in the function that belongs to the function, otherwise the shell will evaluate it.
Another method, using a temporary functions file:
# cat myScript
F=${1:-default}
sed "s/:name:/$F/" funcs.tmp > funcs.sh
. ./funcs.sh
eval somefunction_$F
# cat funcs.tmp
function somefunction_:name: {
echo "$0: Test OK"
}
# ./myScript blah
somefunction_blah: Test OK
# ./myScript
somefunction_default: Test OK
hmm. appending a parameter to a function name is not proving easy.
Ideally I just need 1 script rather than several.
I am getting a little confused.
i would call the script in the following way:
bash myscript SERVICE_NAME
In my script I have:
export SERVICE_NAME=$1
function tnsrec_${SERVICE_NAME} {
..lines of code
}