8

I want to generate environment variable name dynamically and set the value to that variable. I wrote a shell script as below.

temp="$(date +%s)"
echo $temp
export ${temp} = "Test value"
echo "Pass variable ${temp}"

In the above code, generated timestamp should be the key and "Test value" is the value for that key. This key and value have to export to the session.

How can I achieve this using shell script?

1 Answer 1

8

You could use printf -v to create variables dynamically, for example:

temp=somename
echo $temp
printf -v $temp "Test value"
echo $somename

This will output "Test value".

Note that temp="$(date +%s)" won't work, because the output of $(date +%s) is numeric, and variable names in Bash cannot start with a number. You would have to give it a non-numeric prefix, for example:

temp="t$(date +%s)"

To export the variable, you can simply do:

export $temp

Here's a complete example, with proof that the variable really gets exported in the environment:

temp=t$(date +%s)
echo $temp
printf -v $temp "Test value"
export $temp
sh -c "echo \$$temp"

Outputs for example:

t1486060416
Test value
4
  • @AlexanderMills I re-read it and I don't see what you mean. Which part is unclear to you?
    – janos
    Jul 6, 2018 at 4:57
  • I think indirect variables is a better answer? tldp.org/LDP/abs/html/ivr.html Jul 6, 2018 at 5:24
  • I guess it's called indirect references not indirect variables Jul 6, 2018 at 5:25
  • @AlexanderMills Certainly, using indirect references would be possible too. Feel free to post your answer using that technique instead of printf -v.
    – janos
    Jul 6, 2018 at 7:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .