Metaphor
Metaphor

Reputation: 6415

Set environment variable in nested batch file

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?

Upvotes: 1

Views: 4076

Answers (2)

RufusVS
RufusVS

Reputation: 4137

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...

Upvotes: 1

MC ND
MC ND

Reputation: 70961

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.

Upvotes: 5

Related Questions