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

@OP, you can use for loops to capture the return status of your program, if it outputs something other than numbers


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

When executing the following:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

I was getting the error:

%%i was unexpected at this time.

To fix, I changed to use a single % sign like this:

for /f %i in ('application arg0 arg1') do set VAR=%i

Summary:

  • Use %% when in a batch file
  • Use % when outside a batch file (on a command line)

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%