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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With