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?
You could use
printf -v
to create variables dynamically, for example: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:To export the variable, you can simply do:
Here's a complete example, with proof that the variable really gets exported in the environment:
Outputs for example: