How to store the output of batch (CALL) command to

2019-05-21 11:16发布

问题:

I have the batch file which has the command to call second.bat file. It will produce single line of output when it called. I want to store that line into variable.

CALL second.bat

I have tried using the following lines of commands but no use

FOR /F "tokens=* USEBACKQ" %%F IN ('COMMAND') do SET result=%%F
FOR /F "tokens=1 delims= " %%A IN ('COMMAND') DO SET NumDocs=%%A

I don't know what to replace with COMMAND

回答1:

As the help will tell you, COMMAND should be the command you want to run and get the output of. So in your case second.bat. At least it works for me:

@echo off
FOR /F "tokens=*" %%F IN ('second.bat') do SET result=%%F
echo %result%

Note that you cannot use the usebackq option if you're using ' to delimit your command.



回答2:

tl;dr

To complement Joey's helpful answer (which fixes the problem with your 1st command) with a fixed version of both your commands:

::  'usebackq' requires enclosing the command in `...` (back quotes aka backticks)
FOR /F "tokens=* usebackq" %%F IN (`second.bat`) do SET result=%%F

:: No characters must follow "delims="; 'tokens=1' is redundant
FOR /F "delims="           %%F IN ('second.bat') DO SET result=%%F

Note that in this case there's no need for call in order to invoke second.bat (which you normally need in order to continue execution of the calling batch file), because any command inside (...) is run in a child cmd.exe process.


The only thing needed to make your 2nd command work is to remove the space after delims=:

FOR /F "tokens=1 delims=" %%F IN ('second.bat') DO SET result=%%F

delims= - i.e., specifying no delimiters (separators) - must be placed at the very end of the options string, because the very next character is invariably interpreted as a delimiter, which is what happened in your case: a space became the delimiter.

Also, you can simplify the command by removing tokens=1, because with delims= you by definition only get 1 token (per line), namely the entire input (line), as-is:

FOR /F "delims=" %%F IN ('second.bat') DO SET result=%%F

Finally, it's worth noting that there's a subtle difference between tokens=* and delims=:

  • delims= (at the very end of the options string) returns the input / each input line as-is.

  • tokens=* strips leading delimiter instances from the input; with the default set of delimiters - tabs and spaces - leading whitespace is trimmed.