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:
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=%%aFailing to clear the variable’s value when converting a Unix script to Windows batch can be a cause of subtle errors.
–jeroen
via: Windows batch files: How to set a variable with the result of a command? – Stack Overflow.
Leave a Reply