6

In Bash I can create TEMPORARY environment variables on a command line. For eample

DEBUG=foo somecommand

This sets the environmnet variable DEBUG but only for somecommand. When the line is finished DEBUG is no longer set.

Can I do something similar in the Windows Command Processor?

Note: Using SET does not work. That sets the current command processors environment, not the just for the command about to be executed.

To give another example here's a small node.js program that prints the value of a single environment variable

// test.js
console.log(`${process.argv[2]}='${process.env[process.argv[2]]}'`);

Let's run it in bash

$ export FOO=abc
$ node test.js FOO
FOO='abc'

Then let's run it with a temporary setting

$ FOO=def node test.js FOO
FOO='def'

Check that FOO is still abc

$ echo $FOO
abc

How I can accomplish the same thing in the Windows command prompt?

One way seems to be to relaunch the command processor as in

cmd /S /C "set "FOO=def" & node test.js FOO"

Is there another way or is that it?

1
  • "Is there another way or is that it?" I think that is the only way. set foo=bar && echo %foo% && set foo= && echo %foo% does not work :(
    – DavidPostill
    Jan 28, 2018 at 7:32

1 Answer 1

3

Simply use the set command:

C:\>set foo=bar

C:\>echo %foo%
bar

C:\>exit

Open cmd again

C:\>echo %foo%
%foo%

C:\>
2
  • why do i keep getting notifications for this?
    – mekb
    Jun 28, 2021 at 7:40
  • This doesn't do what the OP is asking. In Linux you can set the value of an environment variable for the executed command only. It can be an environment valiable that exists and it doesn't get overriden for other processes. With set, you change the value of the environment variable FOR ALL processes in that session. Oct 22, 2022 at 4:52

You must log in to answer this question.

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