Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch - Store command output to a variable (multiple lines)

I know a way of doing this which is a bit like cheating but the code below creates a temporary file and then deletes it. I don't want that happen. So is there a proper or better way of doing it?

command 2>> "temp"
set /p OUTPUT=<"temp"
del "temp"
echo %OUTPUT%

I know there is a solution which uses for loop but that doesn't work for commands which return more than one line of result. I want to store all of them into my variable. (I tried this code btw)

like image 381
ozcanovunc Avatar asked Jun 24 '15 19:06

ozcanovunc


1 Answers

You can put it into a single variable with including linefeeds.

setlocal EnableDelayedExpansion
set LF=^


REM The two empty lines are required here
set "output="
for /F "delims=" %%f in ('dir /b') do (
    if defined output set "output=!output!!LF!"
    set "output=!output!%%f"
)
echo !output!

But it can be a bit tricky to handle the data later, because of the embedded linefeeds.
And there is still a limit of 8191 characters per variable.

Often it's easier to use an array.

setlocal EnableDelayedExpansion
set "output_cnt=0"
for /F "delims=" %%f in ('dir /b') do (
    set /a output_cnt+=1
    set "output[!output_cnt!]=%%f"
)
for /L %%n in (1 1 !output_cnt!) DO echo !output[%%n]!
like image 122
jeb Avatar answered Nov 10 '22 12:11

jeb