Create dynamic variable name bash and get value

I have a function in bash that get param a string, for example:

MYSQL_DATABASE then I want in my file to create a var named VAR_MYSQL_DATABASE but I can`t get the value.

create_var()
{

    read -p "Enter $1 : " VAR_$1
    printf VAR_$1 // print VAR_MYSQL_DATABASE_NAME instead what I typed, so how do I get the value?
    if [[ -z VAR_$1 ]]; then
        printf '%s\n' "No input entered. Enter $1"
        create_entry $1
    fi  
}

create_var "MYSQL_DATABASE_NAME"

Upvotes: 2

Views: 4215

Answers (3)

chepner
chepner

Reputation: 531055

You can use the printf function with the -v option to "print" to a variable name.

create_var()
{
    while : ; do
        IFS= read -r -p "Enter $1 : " value
        if [[ -n $value ]]; then
            printf -v "VAR_$1" '%s' "$value"
            return
        fi
        printf 'No input entered. Enter %s\n' "$1"
    done  
}

(I've rewritten your function with a loop to avoid what appeared to be an attempt at recursion.)

Upvotes: 2

Inian
Inian

Reputation: 85560

Use the declare built-in in bash,

name="MYSQL_DATABASE"
declare VAR_${name}="Some junk string"
printf "%s\n" "${VAR_MYSQL_DATABASE}"
Some junk string

With the above logic, you can modify how your name variable is controlled, either present locally. If it is passed as argument from a function/command-line do

declare VAR_${1}="Your string value here"

Perhaps you want to achieve something like this,

create_var()
{
    read -p "Enter value: " value
    declare -g VAR_$1="$value"

    dynamVar="VAR_$1"

    if [[ -z "${!dynamVar}" ]]; then
        printf '%s\n' "No input entered. Enter $1"
        create_entry $1
    fi
}

So, here we are creating the dynamic variable using the declare built-in and with the dynamic part VAR_$1 cannot be referenced directly as normal variables, hence using indirect expansion {!variable} to see if the created variable is available.

Upvotes: 4

Aserre
Aserre

Reputation: 5062

Try the following :

#!/bin/bash

create_var() {
        declare -g VAR_$1
        ref=VAR_$1
        read -p "Enter $1: " "VAR_$1"

        echo "inside : ${!ref}"
}

create_var "MYSQL_DATABASE_NAME"
echo "output : $VAR_MYSQL_DATABASE_NAME"

declare -g will make sure the variable exists outside of the function scope, and "VAR_$1" is used to dynamically create the variable names.

Output :

Enter MYSQL_DATABASE_NAME: Apple
inside : Apple
output : Apple

Upvotes: 3

Related Questions