| by Arround The Web | No comments

Batch File for Loop and Batch File for F How to Use Loop Constructs in Your Scripts

A programming construct called a “for loop” enables developers to run a chunk of code repeatedly. Two key loop building blocks in batch files are the for loop and the for /f loop. The for loop can iterate across a range of numbers, a collection of files, or the result of a program in a batch file.

Batch File for Loop and for F: How to Use Loop Constructs in Your Scripts

For Loop

The general syntax for the for loop in batch scripting is as follows:

for %%variable in (list_or_set_or_objects) do (

  command

)

Where:

  • The replaceable parameter %%variable will receive a value from each item in the list, set of objects, etc.
  • list_or_set_or_objects can be the result of a command, a set of files, or a range of values.
  • The block of code, known as a command, is the one that runs for each of the variable.

For example, the following for loop will print the even numbers from 1 to 10:

@echo off

for %%i in (2 4 6 8 10) do (

echo %%i

)

Write the provided code in any text editor you choose, such as Notepad, WordPad, or Notepad++, and save the file with the name ForLoop.bat. The output of even numbers from 1 to 10 will then be displayed on the command screen once you open the command prompt, navigate to the working directory, and enter the batch file’s name along with the .bat extension. In this code, we specify a for loop that iterates through the values 2, 4, 6, 8, and 10, which are the even numbers between 1 and 10. The loop then echoes each even number to the console.

A screen shot of a computer Description automatically generated

Generate 10 Random Unique Airline Ticket Numbers

We can use a loop, along with some random number generation and checking for uniqueness, to generate 10 random and unique ticket numbers for an airline using a for loop in a batch script. To carry out this action, use the following batch script:

@echo off

setlocal enabledelayedexpansion

:: Initialize an array to store generated ticket numbers

set "ticket_numbers="

:: Loop to generate and check for unique ticket numbers

for /l %%i in (1,1,10) do (

:generate

set "random_number=!random!"

set "is_unique=1"

:: Check if the generated number is unique

for %%j in (!ticket_numbers!) do (

if %%j equ !random_number! (

set "is_unique=0"

goto generate

)

)

:: If the number is unique, add it to the array and display it

if !is_unique! equ 1 (

set "ticket_numbers=!ticket_numbers! !random_number!"

echo Ticket %%i: !random_number!

)

)

endlocal

This is how the script functions:

To save the created ticket numbers, it initializes an empty variable called ticket_numbers. It then initiates a loop that runs 10 times, each representing a ticket creation. It uses !random! inside the loop to generate a random number. It determines whether it is unique by comparing the created ticket number to the ones already present in the ticket_numbers array. Until a unique number is identified, it creates another random number if the first one is not unique. If a unique number is discovered, it is added to the variable ticket_numbers and is shown as “Ticket [number]: [random_number]” if it is.

Here is the output:

Nested for loop:

When we need to execute a task within another loop or iterate through numerous sets of values, we utilize nested for loops in batch scripts. A nested for loop that prints multiplication tables from two to five is demonstrated here:

@echo off

setlocal enabledelayedexpansion

:: Outer loop for the first factor (2 to 5)

for /l %%i in (2, 1, 5) do (

echo Multiplication table for %%i:

:: Inner loop for the second factor (1 to 10)

for /l %%j in (1, 1, 10) do (

set /a result=%%i * %%j

echo %%i x %%j = !result!

)

)

endlocal

Here is an explanation of the code:

  • By using the @echo off instruction, the batch interpreter is instructed to stop echoing the commands as they are run.
  • The delayed expansion feature of the “setlocal enabledelayedexpansion” statement prevents variables from being extended until they are needed. The proper operation of the for loop depends on this.
  • The following code will build an outer loop that iterates across the first factors from 2 to 5, according to the comment: Outer loop for the first factor (2 to 5).
  • The do for /l%%i creates the outer loop in the (2, 1, 5) statement. The /l option instructs the loop to repeatedly iterate over a list of numbers, from 2 to 5, increasing each time by one. Each number in the list will be assigned to the variable%%i.
  • The echo Multiplication table for%%i prints the multiplication table header: a statement for the current initial factor.
  • The comment:: Inner loop for the second factor (1 to 10) denotes that the inner loop that will be produced by the code that follows will iterate over the second factor from 1 to 10.
  • The for /l%%j in (1, 1, 10) do statement creates the inner loop. With the /l argument, the loop is instructed to repeatedly iterate over a list of values from 1 to 10, increasing each value by 1. Each number in the list will be assigned to the variable%%j.
  • The product of the current first and second factors is calculated by the set /a result=%%i *%%j statement.
  • The product of the current first and second factors is printed by the echo%%i x%%j =!result! statement.
  • The local variables’ scope is terminated with the endlocal statement.

Output:

For /F Loop

Programmers can use the for /f loop, a more reliable variant of the for loop, to cycle over the results of a command line command. The general syntax of the for /f loop is as follows:

for /f "options" %%variable in ('command') do (

command

)

Where:

  • Tokens specify the delimiters that will be used to split the command output into tokens.
  • Delims is a comma-separated list of delimiter characters.
  • %%variable is a replaceable parameter that will be assigned to each token in the command output.
  • Command is the block of code that will be executed for each token of a variable.

For example, the following for /f loop will print the product on the command line screen that exists in the file products.txt:

@echo off

REM This is a for /f loop

for /f "delims=." %%i in (products.txt) do (

echo %%i

)

Here is the output of the file:

Here’s another illustration of how to parse a command’s output using the for /f loop. In this demonstration, we will retrieve a list of active processes and show their names along with their process identifiers (PIDs). The computer’s active processes will be listed using this code and their process IDs.

Code Snippet:

@echo off

for /f "tokens=1,2" %%a in ('tasklist ^| findstr /i "exe"') do (

echo Process Name: %%a "Process ID:" %%b

)

Here is a complete description of the code:

  • The statement written in line 2 loops over the output of the task list command.
  • The argument tokens=1,2 instructs the loop to only take the first two tokens from the tasklist command’s output. The first token represents the process name, and the second token represents the process ID.
  • The third line of the batch file prints the process name and ID on the command line screen.

To execute the code, use the Run window to open the command prompt, type cmd, and press Enter. Look in the working directory for the ProcessIDs.bat file. Enter the file’s name and extension as given in the snippet:

Here is the output of the file:

Conclusion

This article has covered the for loop and for /f loop in batch files. We’ve also explored multiple examples of how to automate operations using these loops. It is possible to iterate over a range of values, a collection of files, or the results of a command using the flexible loop known as the for. Developers can iterate over the results of a command line command using the for /f loop, a more robust version of the for loop. We can have a for loop inside of another for loop because both loops can be nested. This is helpful for automating difficult tasks.

Share Button

Source: linuxhint.com

Leave a Reply