In this tutorial, you will learn about the batch file for loop. Likewise if else statements, loops are also used to alter the flow of program’s logic.
Looping basically means going through something continuously until some condition is satisfied.
In batch files, there is the direct implementation of for loop only. There does not exist while and do while loops as in other programming languages.
FOR %%var_name IN list DO example_codeHere, the list is the values for which for loop will be executed. One thing to be noticed in batch file for loops is that, variable declaration is done with %%var_name instead of %var_name%.
Let’s take an example for illustrating batch file for loop.
Batch file for loop example
@echo OFF
FOR %%x IN (1 2 3) DO ECHO %%x
PAUSE
Now that we know about the simple implementation of for loop, let’s implement for loop to next level.
Batch file for loop – looping through a range of values
FOR /L %%var_name IN (Lowerlimit, Increment, Upperlimit) Do some_code- /L signifies that for loop is used for iterating through a range of values
- Lower limit is the value from which loop will start until it reaches the Upper limit and the increment is the value with which lower limit will be increased during each iteration
@echo OFF
FOR /L %%y IN (0, 1, 3) DO ECHO %%y
PAUSENow, this program will go through range 0 to 3, incrementing the value by 1 in each iteration.

Batch file for loop – looping through files
So here is the syntax or perhaps an example of for loop for looping through files in particular location.
FOR %y IN (D:\movie\*) DO @ECHO %yThis will go through all the files in movie folder of D: and display the files in output console.
Batch file for loop – looping through directories
FOR /D %y IN (D:\movie\*) DO @ECHO %yNow this will go through even the sub-directories inside movie folder if there exist any.
So, this is all about the batch file for loops. Please practice every piece of code on your local machine for effective learning.

Windows NT 4. Windows 10 Syntax
Runs a specified command for each file in a set of files.
To use the FOR command in a batch program, specify %%variable instead of %variable
Variable names are case sensitive, so %i is different from %I.
If set contains wildcards, then specifies to match against directory names instead of file names.
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would generate the sequence 5 4 3 2 1.
or, with usebackq (not available in Windows NT 4, requires Windows 2000 or later):
filenameset is one or more file names.
Each file is opened, read and processed before going on to the next file in filenameset.
Processing consists of reading in the file, breaking it up into individual lines of text and then parsing each line into zero or more tokens.
The body of the for loop is then called with the variable value(s) set to the found token string(s).
By default, /F passes the first blank separated token from each line of each file.
Blank lines are skipped.
You can override the default parsing behavior by specifying the optional "options" parameter.
This is a quoted string which contains one or more keywords to specify different parsing parameters.
The keywords are:
Some examples might help:
would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces.
Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd.
For file names that contain spaces, you need to quote the filenames with double quotes.
In order to use double quotes in this manner, you also need to use the usebackq option (not available in Windows NT 4), otherwise the double quotes will be interpreted as defining a literal string to parse.
%i is explicitly declared in the for statement and the %j and %k are implicitly declared via the tokens= option.
You can specify up to 26 tokens via the tokens= line, provided it does not cause an attempt to declare a variable higher than the letter ‘z’.
Remember, FOR variable names are global, and you can’t have more than 52 (26 for NT 4) total active at any one time.
You can also use the FOR /F parsing logic on an immediate string, by making the filenameset between the parenthesis a quoted string.
It will be treated as a single line of input from a file and parsed.
would enumerate the environment variable names in the current environment by parsing the output of the SET command.
The modifiers can be combined to get compound results:
In the above examples %i and PATH can be replaced by other valid values.
Just be careful to pick your FOR variable letters to not conflict with any of the format specifier letters if you plan on using the enhanced substitution logic.
The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
page last modified: 2022-03-09
Updated: by

Availability
Call syntax
Windows 2000, Windows XP, and later syntax
Calls one batch program from another.
CALL command now accepts labels as the target of the CALL. The syntax is:
CALL :label arguments
A new batch file context is created with the specified arguments and control is passed to the statement after the label specified. You must “exit” twice by reaching the end of the batch script file twice. The first time you read the end, control returns to after the CALL statement. The second time will exit the batch script. Type GOTO /? for a description of the GOTO :EOF extension that lets you “return” from a batch script.
Substitution of batch parameters (%n) is enhanced. You can now use the below optional syntax:
The modifiers can be combined to get compound results:
In the examples above, %1 and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid argument number. The %~ modifiers may not be used with %* parameter.
MS-DOS, Windows 95, Windows 98, Windows ME syntax
Calls one batch program from another.
The batch-parameters specifies any command line information required by the batch program.
Call examples
call second.bat
Executes the second.bat batch file from within another batch file.
Here’s a one liner, to create a temp script, execute it, then delete it. The script does the sleeping for you (for 3 seconds in this example).
echo WScript.Sleep 3000 > %temp%\sleep.vbs & cscript %temp%\sleep.vbs %sleepMs% //B & del %temp%\sleep.vbsHere’s basically the same thing, written a bit differently:
set sleepMs=3000 & set sleepVbs=%temp%\sleep.vbs & echo WScript.Sleep WScript.Arguments(0) > %sleepVbs% & cscript %sleepVbs% %sleepMs% //B & del %sleepVbs%And then finally, like ping, CScript itself has a timeout option! So, if you enter an infinite loop in the script, you can let the interpreter enforce the duration. Note, this is a “busy” operation, which eats the CPU, and therefore I don’t recommend it when you can use the WScript.Sleep procedure, but I present it as a conceptual option for the sake of completeness:
set sleepSec=3 & set sleepVbs=%temp%\sleep.vbs & echo While True > %sleepVbs% & echo Wend >> %sleepVbs% & cscript %sleepVbs% //B //T:%sleepSec% & del %sleepVbs%To open the Run command Window
The Run command window helps you to run programs and open files and folders. And there are several ways to open up the run command dialog box. This run command box is helpful for you to head straight to the destined program quickly. One of the most commonly used methods is the Shortcut key method. Also, this method is in all versions of Windows. To open the Run command dialog box, you need to press the Win + R key concurrently.
By using the Keyboard shortcut Key:
Win + R
The shortcut key method to the run command box is the most commonly used one. Also, this method is in all versions of Windows. It would help if you pressed the Win + R key concurrently to open the Run command dialog box.

The Purpose of PAUSE command
Syntax
PAUSE
It will display the message, “Press any key to continue. . .”

- To suppress the message, you can use
PAUSE >nul
- By using the CTRL + S in the keyboard, one can use the execution of a batch script, which also works at pausing a single command like a long DIR /s listing. By pressing any key, one can continue the operation.
- Only to give the user time to read some output text, the PAUSE command is used at the end of a script. Alternatively, that can be executed with the CMD/K in the script as
START CMD /k C:\demo\yourscript.cmd
- The above command will execute the script, and the window will remain open for further input. Without having to edit, running the same script in ‘unattended mode‘ is the advantage of the CMD /K.
Real-time example
The PAUSE command is typically used in batch files or scripts to temporarily stop the execution of a command or series of commands.
Here’s an example:
@echo off
echo Backing up system files...
xcopy /s /e C:\Windows\System32 D:\Backup\System32
echo Backup of system files complete.pauseecho Backing up user files...
xcopy /s /e C:\Users D:\Backup\Users
echo Backup of user files complete.
echo Backup complete.Limitations
The PAUSE command is a commonly used command in programming and scripting languages that allows a program to halt its execution for a specified period. However, the PAUSE command has some limitations:
- Single Threaded: The PAUSE command is usually executed on the same thread as the rest of the program. It means that the PAUSE command may not be sufficient if the program needs to perform other tasks during the delay, such as checking for incoming network data or handling user interface events.
- Fixed Time Delay: The PAUSE command can only delay program execution for a fixed time. It means that if the program needs to wait for a specific event to occur, such as user input, the PAUSE command cannot be used.
- Inaccurate Timing: The accuracy of the delay provided by the PAUSE command may not be sufficient for some applications. The delay provided by the PAUSE command depends on factors such as the processing power of the computer and the load on the system. It can make predicting how long the program will be delayed difficult.
- Limited Flexibility: The PAUSE command does not provide much flexibility regarding how the program should behave during the delay. For example, it may not be possible to interrupt the delay and resume program execution early.
Overall, while the PAUSE command can be a useful tool in certain programming situations, its limitations mean it is unsuitable for all scenarios. To address these limitations, developers may need to explore alternative approaches, such as asynchronous or event-based programming.
Fix PAUSE command Access Denied
If you’re encountering an “Access Denied” error when using the PAUSE command, the script or batch file you’re running doesn’t have the necessary permissions to execute.
Here are some possible solutions to fix the Access Denied error:
- Run the script as an administrator: If you’re running the script on a Windows machine, you can try right-clicking on the script file and selecting “Run as administrator”. It will give the script elevated privileges and may resolve the “Access Denied” error.
- Check file permissions: Ensure the user account running the script has permission to access and modify the file. You can check the file permissions by right-clicking on the file, selecting “Properties”, and then navigating to the “Security” tab.
- Disable antivirus software temporarily: Sometimes, antivirus software can block the execution of scripts or batch files. You can try disabling your antivirus software temporarily and then running the script again to see if it resolves the “Access Denied” error.
- Use a different command: If none of the above solutions work, try using a different command instead of PAUSE to achieve the same result. For example, you can use the TIMEOUT command instead, which performs a function similar to PAUSE but with a specified time delay.
Applying these solutions can fix the Access Denied error when using the PAUSE command in your script or batch file.
Related commands
- SLEEP – Wait for x seconds.
- TIMEOUT – Delay that allows the user to press a key and continue immediately.
- PowerShell: Pause.
- Equivalent bash command (Linux): read-p “press any key to continue” or ctrl-z & fg.
Verdict
In this article, the PAUSE command is a useful tool in batch scripting that allows the user to pause the execution of a batch file and prompt for user input. It is often used to provide additional instructions or to confirm that the user wants to proceed with the execution of the batch file. Using the PAUSE command, the user can easily troubleshoot and examine the output or error messages generated up to that point. Overall, the PAUSE command is a simple yet powerful tool that can help make batch scripting more efficient and effective. For more articles, you can visit our homepage.
FAQ
What happens when the PAUSE command is executed in a batch file?
How is the PAUSE command useful in batch scripting?
Can the message displayed by the PAUSE command be customized?
Are there any alternatives to the PAUSE command in batch scripting?
Rate US:
Conditionally perform a command.
IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
ERRORLEVEL
Using the %ERRORLEVEL% variable is a more logical method of checking Errorlevels:
To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
Test if a variable is empty
To test for the existence of a command line parameter – use empty brackets like this
if %_myvar% will never contain quotes, then you can use quotes in place of the brackets IF “%_myvar%” EQU “”
However with this pattern if %_myvar% does unexpectedly contain quotes, you will get IF “”C:\Some Path”” EQU “” those doubled quotes, while not officially documented as an escape will still mess up the comparison.
Test if a variable is NULL
In the case of a variable that might be NULL – a null variable will remove the variable definition altogether, so testing for a NULL becomes:
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
Test the existence of files and folders
IF EXIST filename Will detect the existence of a file or a folder.
The script empty.cmd will show if the folder is empty or not (this is not case sensitive).
Parenthesis
When combining an ELSE statement with parentheses, always put the opening parenthesis on the same line as ELSE.
) ELSE ( This is because CMD does a rather primitive one-line-at-a-time parsing of the command.
Pipes
When piping commands, the expression is evaluated from left to right, so
You can use brackets and conditionals around the command with this syntax:
Placing an IF command on the right hand side of a pipe is also possible but the CMD shell is buggy in this area and can swallow one of the delimiter characters causing unexpected results.
A simple example that does work:
Chaining IF commands (AND).
The only logical operator directly supported by IF is NOT, so to perform an AND requires chaining multiple IF statements:
If either condition is true (OR)
This can be tested using a temporary variable:
Set “_tempvar=”
If SomeCondition Set _tempvar=1
If SomeOtherCondition Set _tempvar=1
if %_tempvar% EQU 1 Command_to_run_if_either_is_true
Delimiters
Test Numeric values
IF only parses numbers when one of the compare-op operators (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
This is an important difference because if you compare numbers as strings it can lead to unexpected results: “2” will be greater than “19” and “026” will be less than “10”.
This behaviour is exactly opposite to the SET /a command where quotes are required.
IF should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647)
You can perform a string comparison on very long numbers, but this will only work as expected when the numbers are exactly the same length:
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
IF does not, by itself, set or clear the Errorlevel.
IF is an internal command.
04.02.2013, 00:56. Показов 321363. Ответов 16

Вдохновившись сообщением от FraidZZ, написал мини-статейку, основанную на изложенных им положениях.
Циклическиe операции FOR
* Примеры под спойлером
Виды наборов для FOR
Для команды For без ключей набором может являться:
1) Маска файлов (или путь + маска файлов)
– в двойных кавычках, или без них:
Результат: список файлов с расширением .txt в текущем каталоге.
IN (*.txt *.bat)
Результат: список файлов с расширениеми .txt и .bat в текущем каталоге.
IN (“C:\Folder 1\Doc_31-12-*.txt”)
Результат: тот же. Но поиск ведется в каталоге C:\Folder 1 (заметьте с пробелом в имени);
имя файла начинается на Doc_31-12-
Прим.: FOR без ключа не умеет выводить список каталогов.
маска файлов – это набор файлов, заданный с помощью подстановочных знаков * и/или ?
где – обозначает 0 или больше любых символов в имени файла.
а – означает 0 или 1 любой символ в имени файла.
2) Строка
– в двойных кавычках, или без них:
Строкой считается любая последовательность символов, если она не содержит знаков маски * или ?
Смысл цикла здесь в том, чтобы разбить такую строку по пробелам (или знакам табуляции)
и выполнить с каждой подстрокой список команд.
Если мы хотим, чтобы какая-то из строк не “билась” по пробелам, укажем ее в двойных кавычках:
Моя гитара
Моя дорогая рыбка
При этом, чтобы не выводились сами кавычки “” мы используем модификатор ~ (тильда) при раскрытии переменной цикла
О других модификаторах переменной цикла можно почитать здесь и здесь.
Не по теме:
О наборах для FOR с ключем /F далее в нижнем спойлере.
часто используется для построчного разбора файла, т.е.
выведет все строки файла 1.txt, который находится в корне диска C.
(Use back quotes) означает, что набор с двойными кавычками подразумевает передачу в цикл имени файла.
означает, что в переменную будет записана вся строка (без разделения по пробелу или знаку табуляции, т.к. стандартный разделитель заменен на NULL (пустой символ).
В такой вариации:
приводит к тому же результату, что и . Означает прекратить разбивку по разделителю после “0-го” токена, т.е. сразу же.
Этот вариант необходим для работы с файлом, путь или имя которого содержит пробелы.
Можно было не использовать , тогда команда приняла бы вид:
но такая конструкция восприняла бы пробел в имени как определение нового файла, поэтому UseBackQ более приемлем.
Примеры под спойлером
Виды наборов для FOR /F
Виды наборов для FOR /F:
1) Набор файлов (задание маски недопустимо!)
Функционал:
чтение содержимого файла(ов) построчно в переменную цикла!
Принцип работы:
Исключение:
принятый по-умолчанию разделитель (пробел и знак табуляции) для этой конструкции цикла не применяется.
А что получится, если установить delims= (возле равно – знак пробела) ?
2) Строка (допускаются практически любые символы)
3) Команда (сначала выполняется она, а уже ее результаты обрабатываются циклом как строка(-и))
1.1. Чтение файла – Набор файлов
1.2. Чтение файла – Набор файлов + UseBackQ
Получаем возможность использовать пробелы.
Результат: выведет содержимое файла 1.txt из каталога c:\folder 1
(заметьте, в имени папки есть пробел).
![]()
Сообщение от Результат
a=Каждое; b=слово; c=в; d=отдельную; e=переменную
2.2. Строка + UseBackQ
Результат такой же.
Сначала выполняется , которая выводит информацию о папках в текущем каталоге.
Вот что попадает под разбор циклу:
3.2. Команда + UseBackQ
Детальную справку можно получить, введя в консоль команду
В отличие, от FOR без ключа, в все токены (все подстроки одной строки) попадают сразу В ПЕРВУЮ ИТЕРАЦИЮ цикла.
Они будут распределены по РАЗНЫМ переменным цикла, идущим в алфавитном порядке, начиная с буквы, заданной после FOR /F %%
Обратите внимание: по умолчанию, цикл выдаёт в результатах только 1-ый токен. Если вам нужно, получить другой, нужно явно указывать модификатор “tokens=xxx”.
Макс. количество токенов и обход ограничения
Максимальное кол-во токенов составляет – 26,
если начальным указать %%a либо %%A (регистр имеет значение)
При этом переход с %%z в %%A не происходит. Остальная часть подстрок опускается.
Можно проверить:
Windows Batch file
IN
Бывают случаи, когда требуется разбить строку по специфическому разделителю и при этом выполнить одну и ту же команду над каждой из подстрок (токеном). Кол-во токенов неизвестно.
Метод показал Anonymоus в теме Символ переноса строки в переменной окружения
Алгоритм заключается в замене разделителя на пробел с одновременным заключением каждого токена в двойные кавычки. Далее строка разбирается обычным циклом FOR без ключа.
А теперь рассмотрим более сложный пример:
1.2. Чтение файла (сложный пример).
Давайте возьмем сложный пример, и раскусим “крепкий орешек” 
Имеем в распоряжении файл 1.txt, который находится рядом с батником.
![]()
Сообщение от Содержимое файла 1.txt
Порядок разбора (или “как прибл. будет думать ком. строка”):
1) – означает каталог, где находится батник, например c:\temp\
4) Итак, первая строка так и называется “первая строка” 
– означает пропустить от начала файла 1-у строку,
значит идем дальше:
7) Теперь смотрим сюда – значит, что первой букве цикла нужно присвоить значение 2-го токена.
Первая буква цикла у нас X. Переменная называется
А второй токен – это подстрока “кода”
С 3-ей строкой потренируйтесь самостоятельно.
Вот такой результат окажется на экране:
Указанная команда выведет:
Прим.: дробные числа командной строкой не поддерживаются.



