Batch script goto statements and for loop
GOTO Statements:
goto
statements are used in batch scripts to create labels and jump to those labels based on certain conditions or program flow. They provide a way to create branches and loops in your batch script. Here's a basic structure of a goto
statement:
:labelNamerem Commands to execute goto :EOF
:labelName
is a user-defined label. It starts with a colon.rem
is a comment (optional) to describe what the section of the code does.goto :EOF
is a common practice to exit a script gracefully when no more commands need to be executed.
Here's an example of a simple goto
statement in a batch script:
@echo offif "%1"=="start" ( goto :start ) else ( goto :end ) :start echo This is the start. goto :EOF :end echo This is the end.
In this example, if the batch script is run with the argument "start," it jumps to the :start
label; otherwise, it goes to the :end
label.
FOR Loops
Batch scripts use for
loops to iterate through lists of items, such as files in a directory or a range of numbers. There are several variations of for
loops, but one of the most commonly used is the for /F
loop, which reads lines from a file or command output.
Here's a simple example of a for /F
loop that reads lines from a text file and echoes each line:
@echo offfor /F %%line in (textfile.txt) do ( echo %%line )
In this script:
/F
specifies that we are working with file content.%%line
is the loop variable that holds the current line.(textfile.txt)
is the source from which we're reading lines.
You can use other variations of for
loops for tasks like iterating through directories or numbers. For example, to loop through numbers from 1 to 10:
@echo offfor /L %%i in (1, 1, 10) do ( echo %%i )
This loop increments the %%i
variable from 1 to 10.
These are the basic concepts of using goto
statements and for
loops in batch scripts. They provide you with the flexibility to create more complex and dynamic batch scripts for various automation and task execution purposes.
0 Comments