Alex Rivera | Logout

Set the value of a variable with the result of a command in a Windows batch file

Asked 2009-05-20T18:34:41.877
109

When working in a Bash environment, to set the value of a variable as the result of a command, I usually do:

var=$(command -args)

where var is the variable set by the command command -args. I can then access that variable as $var.

A more conventional way to do this which is compatible with almost every Unix shell is:

set var=`command -args`

That said, how can I set the value of a variable with the result of a command in a Windows batch file? I've tried:

set var=command -args

But I find that var is set to command -args rather than the output of the command.

Edit
Report

2 Answers

68

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

answered 2009-05-20T19:07:42.217
17

The only way I've seen it done is if you do this:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces:

Microsoft Windows [Version 6.0.6001]

Source

answered 2009-05-20T18:49:59.710

Your Answer