How to generate environment variable name dynamically and export it

10,258

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
Share:
10,258

Related videos on Youtube

Santosh Hegde
Author by

Santosh Hegde

Updated on September 18, 2022

Comments

  • Santosh Hegde
    Santosh Hegde over 1 year

    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?

  • janos
    janos almost 6 years
    @AlexanderMills I re-read it and I don't see what you mean. Which part is unclear to you?
  • Alexander Mills
    Alexander Mills almost 6 years
    I think indirect variables is a better answer? tldp.org/LDP/abs/html/ivr.html
  • Alexander Mills
    Alexander Mills almost 6 years
    I guess it's called indirect references not indirect variables
  • janos
    janos almost 6 years
    @AlexanderMills Certainly, using indirect references would be possible too. Feel free to post your answer using that technique instead of printf -v.