Is it possible to define a function but use a variable to compose its name?
_internal_add_deployment_aliases(){
environment=$1
instanceNumber=$2
shortName=$3
instance="${environment}${instanceNumber}"
ipVar="_ip_$instance"
ip=${!ipVar}
# lots of useful aliases
_full_build_${instance}(){ # how do i dynamically define a function using a variable in its name
#something useful
}
}
Context: I'd like to add bunch of aliases and convenience functions to work with my cloud instances, defining aliases is not a problem, I can easily do
alias _ssh_into_${instance}="ssh -i \"${KEY}\" root@$ip"
and I want to have specific aliases defined when I source from this...
Now when i want to do the same for functions i have a problem, is it possible to do this?
Any help is very very much appreciated :)
You need to use eval for such a problem:
$ var=tmp
$ eval "function echo_${var} {
echo 'tmp'
}"
$ echo_tmp
tmp
An example of your script:
#! /bin/bash
_internal_add_deployment_aliases(){
environment=$1
instanceNumber=$2
shortName=$3
instance="${environment}${instanceNumber}"
ipVar="_ip_$instance"
ip=${!ipVar}
# lots of useful aliases
eval "_full_build_${instance}(){
echo _full_build_${instance}
}"
}
_internal_add_deployment_aliases "stackoverflow" 3 so
_full_build_stackoverflow3 # Will echo _full_build_stackoverflow3
exit 0
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