1

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.

1
  • Note that bash supports ${!key} to do indirect variable referencing. If you're not in charge of the contents of the variables, be very careful of the eval method. key="$(rm -fr / 2>/dev/null & echo Hi)" is not going to lead to happiness. Commented May 2, 2015 at 2:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.