3

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome :-) Just make sure you never run text from an untrusted source through eval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.