InvisibleWolf
InvisibleWolf

Reputation: 1017

How to create a variable in shell script whose name is present in variable?

Let's say I declare two variables key and value like this in shell script

$ key=key1

$ value=value1

now I want to create a variable of name key1 and assign it value value1. What I tried is

$ export ${key}

$ export ${value}

$ $($key=$value)

output: key1=value1: command not found

I don't know how to do this.

Upvotes: 1

Views: 99

Answers (1)

Antxon
Antxon

Reputation: 1943

Use eval $key=$value instead of $($key=$value): The shell substitutes variable values first, and then the $(...) substitution. As there is not command with that name the shell shows command not found in STDERR. Tell the shell to evaluate the substitution result as a regular shell command again by using eval. Later you can export the result with export $key. Using the -x flag for the shell provides a good insight of what happens:

$ key=key1
$ value=value1
$ set -x
$ $key=$value
+ key1=value1
sh: key1=value1: not found [No such file or directory]
$ $($key=$value)
+ key1=value1
sh: key1=value1: not found [No such file or directory]
$ eval $key=$value
+ eval key1=value1
+ key1=value1
$ echo $key1
+ echo value1
value1
$ export $key
+ export key1

Also, be careful when dealing with variables this way: Whitespaces in shell variables can have unexpected results in this kind of constructions.

Upvotes: 2

Related Questions