I need to assign the output of a program to a variable using a MS batch file.
So in GNU Bash shell I would use VAR=$(application arg0 arg1)
. I need a similar behavior in Windows using a batch file.
Something like set VAR=application arg0 arg1
.
In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. We are first setting the value of 2 variables, a and b to 5 and 10 respectively.
Output: The > operator is used to overwrite any file that already exists with new content. The >> operator is used to append to the text file (add to), instead of overwriting it.
One way is:
application arg0 arg1 > temp.txt set /p VAR=<temp.txt
Another is:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
Note that the first %
in %%i
is used to escape the %
after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat
has something like:
for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i echo %datetime%
As an addition to this previous answer, pipes can be used inside a for statement, escaped by a caret symbol:
for /f "tokens=*" %%i in ('tasklist ^| grep "explorer"') do set VAR=%%i
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