Write value to environment variable from script

I try to write value in environment variable from my script, but somthing I don’t see changes, but I see as script write value to log. What is wrong I do?


val=$(openssl rand -hex 32)
export MY_VALUE=$val
echo "$(date) - New VALUE: $val" >> /var/log/mylog.log

That script creates a bash process and the env variable is set inside that process. When that process exits, the environment goes with it.

If you are trying to use a script to set a variable to the parent process, you can use declare instead of export

However, depending on what you are trying to do, this may not be the right solution.

In cases like this, it is better to describe what you want to accomplish as opposed to a detailed question like this.

I want to generate jwt secret key every 24 hours and save this key to environment variable, I using cronie that schedule my script.

How do you want to use the generated key?
You say it is a secret key, but looks like anyone can see it…

You could simply store the key into a file and use it from there.

Something like this:

# file for storing the key
touch /home/your-account/.secret-key     # change your-account to your username

# create and store the key
openssl rand -hex 32 > /home/your-account/.secret-key

# use the key somewhere
keyval=$(cat /home/your-account/.secret-key)

Is this what you are trying to do?

1 Like

I don’t think you can use environment variables like that. The scope of the variable is too limited.

1 Like

I Thinked about this solution but not apply. So if environment variables is limited. Then your answer is a best way, because file can limit to write end edit. Thank you!

That’s a useless use of cat – you’re launching a separate program from your script just to get the contents of a file into a variable. In fact, there is almost never any need to use cat in a Bash script, as Bash provides facilities for that.

Don’t do that… Do this instead:


Indeed. The OP might want to consider the security implications of that. Depending on the use case, it may or may not be a good idea.


This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.