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?

1

1 Answer 1

13

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.

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

5 Comments

Wow, that's some fugly scripting but it just might work. I'm going to try it now!
Can you explain the meaning of %%A rather than %A in the context of a batch file?
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 "%%".
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.
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.

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.