Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file 'for' loops - multiple lines

Why will the following lines work in a batch file?

 for  %%a in ("C:\Test\*.txt") do set FileName=%%~a  echo Filename is: %FileName% 

But these won't?:

 for  %%a in ("C:\Test\*.txt") do (      set FileName=%%~a      echo Filename is: %FileName%  ) 

It's like the "a" variable isn't retained over the second line. Why is this and how do I use the contents of "a" as in the second example?

like image 378
michaelekins Avatar asked Oct 01 '13 16:10

michaelekins


Video Answer


1 Answers

It is because everything between the parentheses is loaded as one line. So %FileName% is expanded (at load time) before it is set (at run time). If you need to use the second format, you need to enable delayed expansion. Then you will have difficulty if the filename contains a !. This would work if there are no parentheses in filenames.

 setlocal enabledelayedexpansion  for  %%a in ("C:\Test\*.txt") do (      set FileName=%%~a      echo Filename is: !FileName!  )  endlocal 
like image 178
RGuggisberg Avatar answered Sep 28 '22 01:09

RGuggisberg