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

天涯浪子 提交于 2019-12-06 07:43:35
Joey

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!