Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix bash dynamically add function using variable in its name

Tags:

bash

unix

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

like image 217
justnooobs Avatar asked Sep 03 '26 19:09

justnooobs


1 Answers

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
like image 178
Bayou Avatar answered Sep 05 '26 13:09

Bayou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!