Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a variable inside a loop for /F

Tags:

batch-file

cmd

I made this code

dir /B /S %RepToRead% > %FileName%  for /F "tokens=*" %%a in ('type %FileName%') do (     set z=%%a     echo %z%     echo %%a ) 

echo %%a is working fine but echo %z% returns "echo disabled".

I need to set a %z% because I want to split the variable like %z:~7%

Any ideas?

like image 314
Chris Avatar asked Dec 10 '12 16:12

Chris


People also ask

Can you create a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

What does Setlocal Enabledelayedexpansion do?

ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /? ) Its effect lives for the duration of the script, or an ENDLOCAL : When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

How do you loop a batch file?

Pressing "y" would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file.

Was unexpected at this time batch file?

If you are getting this error on your IF statement check if used or not your double equals to compare your variable. Eg. This throws "=1 was unexpected at this time." To correct this add another equals sign.


1 Answers

There are two methods to setting and using variables within for loops and parentheses scope.

  1. setlocal enabledelayedexpansion see setlocal /? for help. This only works on XP/2000 or newer versions of Windows. then use !variable! instead of %variable% inside the loop...

  2. Create a batch function using batch goto labels :Label.

    Example:

    for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a goto End  :Foo set z=%1 echo %z% echo %1 goto :eof  :End 

    Batch functions are very useful mechanism.

like image 114
David Ruhmann Avatar answered Sep 24 '22 00:09

David Ruhmann