8

In UNIX you can assign the output of a script to an environment variable using the technique explained here - but what is the Windows equivalent?

I have a python utility which is intended to correct an environment variable. This script simply writes a sequence of chars to stdout. For the purposes of this question, the fact that my utility is written in python is irrelevant, it's just a program that I can call from the command-prompt which outputs a single line of text.

I'd like to do something like this (that works):

set WORKSPACE=[ the output of my_util.py ]

After running this command the value of the WORKSPACE environment variable should contain the exact same text that my utility would normally print out.

Can it be done? How?


UPDATE1: Somebody at work suggested:

python util.py | set /P WORKSPACE=

In theory, that would assign the stdout of the python-script top the env-var WORKSPACE, and yet it does not work, what is going wrong here?

Community
  • 1
  • 1
Salim Fadhley
  • 22,020
  • 23
  • 75
  • 102
  • 1
    It has already been asked - [How do I get the result of a command in a variable in windows?](http://stackoverflow.com/questions/108439/) – Piotr Dobrogost Oct 25 '11 at 00:03

1 Answers1

12

Use:

for /f "delims=" %A in ('<insert command here>') do @set <variable name>=%A

For example:

for /f "delims=" %A in ('time /t') do @set my_env_var=%A

...will run the command "time /t" and set the env variable "my_env_var" to the result.

Remember to use %%A instead of %A if you're running this inside a .BAT file.

William Leara
  • 10,595
  • 4
  • 36
  • 58
  • Wow, that's some fugly scripting but it just might work. I'm going to try it now! – Salim Fadhley Apr 29 '10 at 16:02
  • 1
    Can you explain the meaning of %%A rather than %A in the context of a batch file? – Salim Fadhley Apr 29 '10 at 16:04
  • 1
    In batch files, "%" is a reservered character. For example, %1 refers to the first argument passed on the command line. So, in cases where you need to use a "%" where you're not referring to command line arguments, you double it up like "%%". – William Leara Apr 29 '10 at 16:12
  • This is one of the ugliest trick I often have to use. It's amazing how often in batch you have to use features intended for completely different uses to supply to the fundamental things that are missing. – Matteo Italia Apr 29 '10 at 17:13
  • 4
    Keep in mind though, that if the command has more than a single line of output you will only retain the last one in the variable. – Joey Apr 30 '10 at 08:05