Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set commands output as a variable in a batch file

Is it possible to set a statement's output of a batch file to a variable, for example:

findstr testing > %VARIABLE%  echo %VARIABLE% 
like image 990
Dennis Avatar asked Jun 15 '11 15:06

Dennis


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.


1 Answers

FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO ( SET var=%%F ) ECHO %var% 

I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.

Now if your output will contain multiple lines, you can do this

SETLOCAL ENABLEDELAYEDEXPANSION SET count=1 FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (   SET var!count!=%%F   SET /a count=!count!+1 ) ECHO %var1% ECHO %var2% ECHO %var3% ENDLOCAL 
like image 80
Anthony Miller Avatar answered Oct 23 '22 22:10

Anthony Miller