Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a string variable name from the value of another string

Tags:

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.

like image 213
NeonGlow Avatar asked Dec 05 '12 04:12

NeonGlow


People also ask

How do you create a variable name from a string?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you assign a string to a variable?

To assign it to a variable, we can use the variable name and “=” operator. Normally single and double quotes are used to assign a string with a single line of character but triple quotes are used to assign a string with multi-lines of character.

Can you name a variable using another variable?

No, you can't, and it makes no sense honestly to have a feature like that. Show activity on this post. No, and it doesn't make any sense. Variable (or more precisely, local) names are only important at compile-time, and they only have values at runtime.


1 Answers

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" 
like image 113
gniourf_gniourf Avatar answered Sep 22 '22 15:09

gniourf_gniourf