Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 715
Francis Avatar asked May 20 '09 18:05

Francis


People also ask

How do you set a 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.

What is @echo off in batch script?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.


2 Answers

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.

like image 170
nik Avatar answered Sep 20 '22 00:09

nik


One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a 

does not have the same semantics as the Unix shell statement:

theValue=`command` 

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue= for /f "delims=" %%a in ('command') do @set theValue=%%a 

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

like image 23
Jonathan Headland Avatar answered Sep 17 '22 00:09

Jonathan Headland