Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Windows shell scripting (cmd.exe) how do you assign the stdout of a program to an environment variable?

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?

like image 317
Salim Fadhley Avatar asked Apr 29 '10 15:04

Salim Fadhley


People also ask

How do I set environment variable in CMD?

2.2 Set/Unset/Change an Environment Variable for the "Current" CMD Session. To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.

How do I set an environment variable in Windows?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.

How do I find environment variables in Windows 10 CMD?

On WindowsSelect Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.

How do I export a variable from the command line in Windows?

The Windows equivalent of the export command is the “setx” command or the “set” command. The “setx” command is utilized to set environment variables permanently. However, the “set” command can set variables temporarily (for one session only).


1 Answers

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.

like image 194
William Leara Avatar answered Sep 21 '22 20:09

William Leara