- 1 year ago
windows batch script .bat for loop
In a Windows batch script (.bat
), you can use a for
loop to iterate over a set of items, perform actions on each item, or execute commands based on the items in the loop. There are different types of for
loops in batch scripting, and the most commonly used ones are the for /F
loop and the for
loop with the in
clause.
Here's an explanation of both types of for
loops:
for /F
loop: This type of loop is used to read and process the output of a command or the content of a file.Syntax:
batchfor /F "options" %%variable in ('command_or_file') do (
rem Actions to perform on %%variable
)
Example - Looping through the lines of a text file and displaying each line:
batch@echo off
for /F "tokens=*" %%line in (example.txt) do (
echo %%line
)
for
loop within
clause: This type of loop is used to iterate over a specified set of items.Syntax:
batchfor %%variable in (item1 item2 item3 ...) do (
rem Actions to perform on %%variable
)
Example - Looping through a list of strings and displaying each item:
batch@echo off
for %%item in (apple banana cherry) do (
echo %%item
)
The variable used in the loop (e.g., %%variable
, %%line
, %%item
) is a placeholder for the current item being processed in the loop. You can use any valid variable name.
Remember that when you run a batch script directly from the command prompt, use a single percent sign %
for variables. However, when you use the same script in a batch file, you need to double the percent signs %%
for the variables.
Be careful with the syntax and indentation when using for
loops in batch scripts, as batch scripting is sensitive to whitespace and special characters.
Additionally, keep in mind that the examples provided are simple illustrations of the for
loops. In real-world scenarios, you may need to adjust the loop options, tokens, or delimiters based on your specific use case.