The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,969 other subscribers

Windows batch files: How to set a variable with the result of a command (via: Stack Overflow)

Posted by jpluimers on 2013/12/11

One of the easy things in *nix is to set the value of an environment with the output of a command.

Something like this is possible in Windows too, but you have to instruct Windows to keep an empty set of delimiters to capture the full first line.

There is also a small but important difference between Windows and *nix upon command failure: *nix will always return an empty value, but in Windows you must make sure to empty the value first.

Thanks Jesse Dearing for this summary:

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]

and aven more thanks to for Jonathan Headlandthis very nice answer explaining the subtle difference:

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:


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.


via: Windows batch files: How to set a variable with the result of a command? – Stack Overflow.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: