Search code examples
bashunix

Creating a string variable name from the value of another string


In my bash script I have two variables CONFIG_OPTION and CONFIG_VALUE which contain string VENDOR_NAME and Default_Vendor respectively.

I need to create a variable with name $CONFIG_OPTION ie VENDOR_NAME and assign the value in CONFIG_VALUE to newly created variable.

How I can do this?

I tried

$CONFIG_OPTION=$CONFIG_VALUE

But I am getting an error on this line as

'./Build.bash: line 137: VENDOR_NAME="Default_Vendor": command not found'

Thanks.


Solution

  • I know that nobody will mention it, so here I go. You can use printf!

    #!/bin/bash
    
    CONFIG_OPTION="VENDOR_NAME"
    CONFIG_VALUE="Default_Vendor"
    
    printf -v "$CONFIG_OPTION" "%s" "$CONFIG_VALUE"
    
    # Don't believe me?
    echo "$VENDOR_NAME"