Tuesday, February 22, 2011

Using Variables Inside Loops

There are two really useful constructions in batch files: conditions (IFs) and loops (FORs). Both of theme are extremely widely used, and both of them have some difficulties for beginners. Here we are going to discuss one of these difficulties concerning loops.
The difficulty is called 'local variables'. As far as you know, to retrieve the value of certain variable, you have to use the following construction: %variable_name%. But if you use your variable inside a loop, and its value is being changed on each iteration, you should not use this way to access the variable. Try to place %variable_name% inside a loop, and you will retrieve the same value every time. Thus you have to use setlocal enabledelayedexpansion and write !variable_name! instead (don't forget to use endlocal after a loop).
It is not very hard to follow this small tip, just don't forget to use it while you write batch files.

No comments:

Post a Comment

Translate