Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign output of a program to a variable using a MS batch file

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.

like image 516
initialZero Avatar asked Feb 24 '10 02:02

initialZero


People also ask

How do I assign a variable to a batch file?

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.

How do I write the output of a batch file?

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.


2 Answers

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% 
like image 151
Carlos Gutiérrez Avatar answered Sep 21 '22 15:09

Carlos Gutiérrez


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 
like image 37
Renat Avatar answered Sep 18 '22 15:09

Renat