1

I am trying to factor out a piece of a batch file that sets an environment variable to another batch file. This piece is somewhat involved and I would rather not repeat it in multiple batch files. I won't over-complicate this post with the actual code I'm trying to run in the nested batch file, but will provide a simple example that shows what I'm trying to do and reproduces the problem.

Batch1.cmd

cmd.exe /c setvar.cmd abc def
set abc

setvar.cmd

set var=%1
set val=%2
set %var%=%val%

The error returned for "set abc" in Batch1.cmd is this:

Environment variable abc not defined

I imagine cmd.exe starts up a new environment, because on return to Batch1.cmd, the variable does not exist.

Is there a way I can nest a batch file and keep the environment it creates?

2 Answers 2

5

The environment block is not shared between processes. As you are starting a new cmd instance a separate environment block is created, changed and destroyed before returning the control to the current batch file, that will not see any change as it was done in a different process.

Use call setvar.cmd abc def to start the nested batch file in the current process.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the setx <var> <val> command to set an environment variable more persistently. For example:

setx WEBCAM_ADDR 192.168.0.101

(Note: There is NO equals sign (=) as with the regular set command)

I just went through this issue, trying to run batch files from windows. This is better than having to write, say, a configuration file somewhere...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.