Question: CODE with details
=================

```
#!/usr/bin/bash -xv

```

FUNCTION\_DYNAMIC
=================

```
eval "function APP_$i_$j
{
    `enter code here`
}"

```

DEFINING\_FUNC\_TO\_CALCULATE\_VALUE
====================================

```
APP_VAR_MKT()
{
    for i in `cat ${SERVER}`
    do
        for j in `cat ${ZONE}`
        do
            shopt -s expand_aliases
            alias name="APP_${i}_${j}"
            declare -fp "APP_${i}_${j}"
        done
    done
}

```

MAIN
====

```
SERVER_NAME=/path/servers_file
ZONE=/path/zones_file

```

DECLARING FUNCTION with variable in it
======================================

```
APP_VAR_MKT

```

Answer: 
**Disclaimer:** Declaring functions dynamically is not the approach you should use. See [chepner's answer](https://stackoverflow.com/a/48052760/6176817), that is definitely the preferred way! 

However, if you really want to create the name dynamically, here is another way to do it, that is a little less problematic than `eval`:

```
#!/usr/bin/env bash 

SERVER_NAME=foo
ZONE=bar

shopt -s expand_aliases
alias name="APP_${SERVER_NAME}_$ZONE"

name() { 
   echo hello
}

declare -fp "APP_${SERVER_NAME}_${ZONE}"

```

The output of `declare` shows that `APP_foo_bar` has been declared:

```
APP_foo_bar () 
{ 
    echo hello
}

```

---

Now, this works to *some degree*. You have to be very cautious if the input is not under your control. This can be potentially dangerous:

```
#!/usr/bin/env bash 

SERVER_NAME='foo() { echo hi; }; echo ouch;'
ZONE=bar

shopt -s expand_aliases
alias name="APP_${SERVER_NAME}_$ZONE"

name() { 
   echo hello
}

declare -fp APP_foo
declare -fp _bar

```

When the *right* `alias` is used, this approach can be used to execute arbitrary code. The output of this script is:

```
ouch
APP_foo () 
{ 
    echo hi
}
_bar () 
{ 
    echo hello
}

```

Not only were the wrong functions declared, `echo ouch` got executed! Now imagine if I used `rm -rf *`. Using `eval` presents the exact same problem. 

---

**Conclusion:** Don't do it :)
You should not do this, unless you have a good reason for it - functions are reusable encapsulations of code, and their names should not change normally. Also you should not use eval because it is very dangerous. So be warned.

What you can do if you absolutely must is use eval:

```
#!/bin/bash

eval "function APP_${SERVER_NAME}_${ZONE}
{
    echo 'XXX'
}"

APP_${SERVER_NAME}_${ZONE}

```

The result:

`XXX`