0

I wonder how can we get the latest value of an environment variable in a bash shell script. Problem I am having is, I have a environment variable which can be changed externally multiple times. But when I use that variable in a shell script, it always display the value which was the value during the start. for example I have written a shell script there is a env variable x is 10

echo $x   #Here this prints 10
sleep 20  #here during the sleep I am changing the value to 5
echo $x   #Here even after value is changed to 5 , it prints 10.

Actual execution is below:

# ./temp.sh &
[1] 915
# 10

# export x=5
# 10

[1]+  Done                    ./temp.sh
#
2

An environment variable is not meant to do such a trick. The script inherits the environment as a copy once it is run; the two environments are then independent.

You may need to look for interprocess communication methods. If you really, really have to do this via variable, check this; although it's not the right way to communicate with a running process in normal usage.

1

Environment variables are specific to each process. When a process starts, it is given a copy of the environment (built up by the process which is starting it), and once it's started no other process can touch that copy.

In your example, when you change the value of x, you're doing so in the shell you're running. By exporting variables, you tell the shell that you want them to be copied to the environment of processes which the shell starts subsequently, but that can't affect the values of variables in processes which have already started. So temp.sh, which has its own shell running it, gets the value of x at the time it starts, but subsequent changes made to x in the interactive shell you're using aren't visible to the shell running temp.sh.

(Strictly speaking root could change the environment of a running process, but that's beyond the scope of this answer.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.