2

I would like to access the updated environment variable in 2nd Batch file, which is changing continuously using 1st batch file.

The e.var changing continuously using 1st batch file but I am getting only one value assigned to the E.variable after starting 2nd batch file.

For Example:

1st batch file:

:start   
setx ev=%random%
sleep 5s
goto start:

2nd batch file:

:start    
echo %ev%
sleep 10s  
goto start:
1
  • 3
    This SO question answers your stated question. However, I would like to ask you what you are trying to solve - your current example seems like a rather hackish attempt to do something, and there might be a more elegant way to do this something if you tell us what it is.
    – Bob
    Mar 10, 2013 at 14:09

2 Answers 2

5

Probably there is some misunderstanding regarding environment variables. Those are not shared between running processes (think about all the chaos this would lead to), but every process runs in it's own environment.

Changing environment variable ev of process A will have no effect on setting or changing the environment variable ev of process B.

The new environment for a starting process is created by copying the environment of its "parent" - the process that started it. That's why you still see the value once set to the environment variable ev in process A. It got copied to the environment of your new process running your 2nd batch.

While the variable ev in A's environment keeps constantly changing the variableev in B's environment will keep constant.

1

These 2 .bat files work fine when run in 2 separate Command Prompt windows

1st.bat:

@echo off
:start
setx ev %random%
timeout /t 5 /nobreak >nul
goto start:

2nd.bat:

@echo off
:start
for /f "tokens=2*" %%A in ('REG QUERY "HKCU\Environment" /v ev ^|FIND "ev"') DO set ev=%%B
echo %ev%
timeout /t 10 /nobreak >nul
goto start:

You must log in to answer this question.

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