Отобразит, установит или удалит переменную окружения cmd.exe.
SET [variable=[string]]
variable Указывает имя переменной окружения.
string Указывает набор символов для присваивания переменной окружения.
Команда SET без параметров отобразит список переменных текущего окружения.
Если разрешены расширения команд (Command Extensions, они разрешены по умолчанию), то команда SET меняется следующим образом:
Когда команда SET вызывается только с именем переменной, без знака равенства или значения, то она отобразит значение всех переменных, префикс которых совпадает с именем, переданным команде SET. Например:
SET p
.. отобразит все переменные, имя которых начинается с буквы ‘P’ или ‘p’.
Команда SET установит переменную окружения ERRORLEVEL в 1, если имя переменной не было найдено в текущем окружении.
Команда SET не позволяет использовать символ равенства в имени переменной.
Были добавлены две новые опции:
SET /A expression
SET /P variable=[promptString]
Опция /A указывает, что строка справа от знака равенства — вычисляемое числовое выражение. Средство оценки выражений является довольно простым и поддерживает следующие операции, в порядке уменьшения приоритетности:
() — группирование
! ~ — — унарные операторы
* / % — арифметические операторы
+ — — арифметические операторы
<< >> — логический сдвиг
& — побитная операция И (AND)
^ — побитная операция ИСКЛЮЧАЮЩЕЕ ИЛИ (XOR)
| — побитная операция ИЛИ (OR)
= *= /= %= += -= — присваивание
&= ^= |= <<= >>=
, — разделитель выражения
Если вы используете любой из логических или модульных операторов, то вам нужно будет заключить строку выражения в кавычки. Любые нечисловые строки в выражении рассматриваются как имена переменных среды, значения которых преобразуется в числа перед их использованием. Если имя переменной окружения указано, то в настоящее время не определено в окружении, то эта переменная вычисляется как 0. Это позволяет делать арифметику со значениями переменных окружения среды без необходимости вводить все эти знаки % для получения значений переменных. Если SET/A выполняется из командной строки за командного скрипта, то будет отображено конечное значение выражения. Оператор присваивания требует указания имени переменной в левой части выражения. Числовые значения это десятичные числа, если они не снабжены префиксом 0x для шестнадцатеричных чисел или префиксом 0 для восьмеричных чисел. Таким образом, 0x12 это то же самое значение, что и 18 или 022. Обратите внимание на то, что использование восьмеричных значений может вызвать путаницу: 08 и 09 это недопустимые значения, потому что 8 и 9 не используются для цифр восьмеричных значений.
Опция /P позволит вам установить значение переменной в строку, введенную пользователем. Покажет указанное сообщение приглашения promptString перед чтением строки ввода. Строка promptString может быть пустой.
Подстановка переменных среды была расширена следующим образом:
%PATH:str1=str2%
Это выражение расширит переменную окружения PATH, подставляя каждое вхождение «str1» в расширенный результат «str2». «str2» может быть пустым, что эффективно удалит все вхождения «str1» из расширенного вывода. «str1» может начинаться со звездочки, и в этом случае она будет совпадать с любыми значениями от начала расширенного вывода первого вхождения оставшейся порции str1.
В выражении можно также указать части строк. Например (10 это смещение от начала, 5 это длина):
%PATH:~10,5%
Это выражение расширит переменную окружения PATH, и затем использует только 5 символов, которые начинаются с 11-го символа (смещение 10) расширенного результата. Если длина (в этом примере 5) не указана, то по умолчанию будет взята остальная часть значения переменной. Если любое из чисел (смещение или длина) отрицательное, то используемое число является длиной значения переменной среды, добавляемого к указанному смещению или длине. Например:
%PATH:~-10%
Это выражение извлечет последние 10 символов переменной PATH. Другой пример:
%PATH:~0,-2%
Это выражение извлечет все символы переменной PATH, кроме последних двух.
И наконец, была добавлена поддержка отложенного расширения переменной окружения. По умолчанию эта поддержка всегда запрещена, но может быть разрешена/запрещена опцией командной строки /V интерпретатора CMD.EXE. См. CMD /?
Отложенное расширение переменной среды полезно для обхода ограничений текущего расширения, которое произойдет при чтении строки текста, а не при её выполнении. Следующий пример демонстрирует проблему немедленного расширения переменной:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "%VAR%" == "after" @echo Если вы это видите, то работает )
Это пример никогда не отобразит сообщение echo, поскольку %VAR% в ОБОИХ операторах IF подставляется, когда происходит чтение первого оператора IF, потому что он логически включает тело IF, который является составным оператором. Так что IF внутри составного оператора фактически выполняет сравнение «before» с «after», которые никогда не равны. Аналогично, следующий пример не сработает как ожидалось:
set LIST= for %i in (*) do set LIST=%LIST% %i echo %LIST%
Это НЕ будет создавать список файлов в текущем каталоге, но вместо этого просто установит переменную LIST на последний найденный файл. Опять же, это связано с тем, что %LIST% расширяется только один раз, когда считывается инструкция FOR, и в это время переменная LIST пуста. Таким образом, фактический цикл FOR, который мы выполняем:
for %i in (*) do set LIST= %i
.. что просто установит LIST в последний найденный файл.
Отложенное расширение переменной окружения позволит вам использовать другой символ (восклицательный знак) для расширения переменных среды во время выполнения. Если включено отложенное расширение переменной, то приведенные выше примеры могут быть записаны следующим образом для работы по их назначению:
set VAR=before if "%VAR%" == "before" ( set VAR=after if "!VAR!" == "after" @echo Если вы это видите, то работает )
set LIST= for %i in (*) do set LIST=!LIST! %i echo %LIST%
Если разрешены Command Extensions, то существует несколько динамических переменных окружения, которые могут быть развернуты, но не отображаются в списке переменных, показываемых командой SET. Эти значения переменных вычисляется динамически при каждом расширении значения переменной. Если пользователь явно определяет переменную с одним из этих имен, то это определение будет переопределять динамически:
%CD% — расширяется в строку текущей директории.
%DATE% — расширяется в текущую дату с использованием такого же формата, какой использует команда DATE.
%TIME% — расширяется в текущее время в таком же формате, какой использует команда TIME.
%RANDOM% — расширится в случайное десятичное число между 0 и 32767.
%ERRORLEVEL% — расширится в текущее значение ERRORLEVEL.
%CMDEXTVERSION% — расширится в текущий номер версии Command Processor Extensions.
%CMDCMDLINE% — расширится в оригинальную командную строку, которой был запущен Command Processor.
%HIGHESTNUMANODENUMBER% — расширится в самое большоe число NUMA node на этой машине.
To create a batch file that prompts the user to press any key to continue, follow these steps:
1. Open Notepad or any other text editor.
2. Type the command pause in the editor.
3. Save the file with a .bat extension (e.g. «example.bat»).
The pause command in batch files pauses the execution of the script until the user presses any key. When the user presses a key, the script continues executing from where it left off.
Here is an example of a batch file that prompts the user to press any key to continue:
@echo off
echo This is a sample batch file.
pause
echo Batch file execution has resumed after the pause command.
When the user runs this batch file, they will see the message «This is a sample batch file.» After pressing any key, they will see the message «Batch file execution has resumed after the pause command.»
-
Use
/WAIT
to Wait for the Command to Finish Execution in Batch Script -
Use the
TIMEOUT
Command to Delay the Execution in Batch Script -
Use the
PAUSE
Command to Pause the Execution in Batch Script -
Use the
CALL
Command to Wait for the Command to Finish Execution in Batch Script -
Use the
&&
Operator to Wait for Command to Finish Execution in Batch Script -
Use a Loop to Wait for Command to Finish Execution in Batch Script
-
Conclusion
Batch scripting in Windows allows users to automate tasks by writing a series of commands that the system can execute. Often, it’s crucial to ensure that a command finishes its execution before moving on to the next one.
There are multiple commands and installation processes in a Batch file that usually take some time to complete. But when a Batch file is run, it does not wait for a command process to finish; it executes all commands line by line.
It is important to make those commands wait for them to finish and then execute the next commands. For a process to wait until it is finished, we use the /wait
parameter with the START
command.
Instead of starting a command, if there is a need to insert delays in the Batch file for some time interval, we can use commands such as TIMEOUT
and PAUSE
to stop the execution of the next process for a short interval of time or until a key is pressed.
This tutorial illustrates different ways to wait for a command or a program to finish before executing the next command in the Windows Batch file.
Use /WAIT
to Wait for the Command to Finish Execution in Batch Script
The /WAIT
parameter is used with the START
command in a Batch file. It instructs the command prompt to wait for the command or application to complete its execution before moving on to the next line in the Batch script.
This parameter is particularly useful when you need to launch an application or script and ensure it finishes before proceeding.
The syntax of the START
command with the /WAIT
parameter is as follows:
START "title" [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
[parameters]
/WAIT
: This is the parameter we’re focusing on in this guide. It causes theSTART
command to wait for the executed command or program to finish before proceeding with the Batch script.
When we start a program in a Batch file using the START
command, we can wait until the program is finished by adding /wait
to the START
command. Even if there are multiple commands, /wait
can be used for each process to finish and move to the next one.
Also, the parameter /B
is used to stay in the same process without creating a new window. The START
command without the /B
parameter opens the program or command in a new window.
Wait for a Command to Finish Execution
For example, we need to wait for a command to finish execution before running the next one.
@echo off
echo starting first program.
START /B /WAIT cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txt
echo The first program is executed successfully.
START /B systeminfo >> stdout.txt
echo All the programs are executed successfully
cmd /k
This Batch script executes two programs sequentially. It starts by running testfile1.bat
and waits for it to finish before echoing a success message.
Then, it gathers system information using systeminfo
and appends the output to output.txt
. Finally, it opens a new command prompt window for further interaction.
Output:
Wait for the .exe
File to Finish Execution
Another example is where we need to run a .exe
file and wait until the execution is done completely.
@echo off
echo starting first program.
START /B /WAIT JRuler.exe
echo The first program is executed successfully.
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script first runs an application called JRuler.exe
and waits for it to finish. It then echoes a success message.
Next, it gathers system information using the systeminfo
command and appends the output to a file called output.txt
. Finally, it opens a new command prompt window for further interaction.
Output:
As soon as you close the .exe
file, the second program will begin execution. cmd /k
in the last line is used to prevent the command prompt from exiting after execution.
If there are multiple programs, you can use /WAIT
with each command to wait until the execution is finished. The START
command with the /WAIT
parameter doesn’t have any timeout, i.e., it does not matter how long the process will take to finish; it will wait until the process is completed.
@echo off
START /WAIT install1.exe
START /WAIT install2.exe
/WAIT
can only be used with the START
command. We can insert a time delay for other commands by using the TIMEOUT
and PAUSE
commands.
Use the TIMEOUT
Command to Delay the Execution in Batch Script
The TIMEOUT
command is used in Batch scripts to introduce a delay in the execution. It allows you to pause the script for a specified amount of time, measured in seconds.
This is particularly useful when you need to ensure that a process or task is completed before moving on to the next step.
The range for the TIMEOUT
command varies between -1
and 100000
. If the delay is set to -1
, it will act as a pause
command to wait until a key is pressed.
As in the previous method, we can replace the /wait
by inserting the TIMEOUT
command with the /t
parameter. The syntax for the TIMEOUT
command is given below:
TIMEOUT [/T timeout] [/NOBREAK]
/T timeout
: This option specifies the delay time in seconds. If omitted, the default delay is10
seconds./NOBREAK
: This option allows users to interrupt the countdown by pressing any key. If omitted, the countdown cannot be interrupted.
Let’s take the example in the previous method and add a time delay of 30
seconds after the execution of the first program.
@echo off
echo starting first program.
START /B JRuler.exe
TIMEOUT /t 30
echo The first program is executed successfully.
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script automates the execution of two programs. It starts with JRuler.exe
and waits for 30
seconds.
Afterward, it echoes a success message. Then, it runs the systeminfo
command and appends the output to output.txt
.
Finally, it opens a new command prompt window for further interaction.
Output:
After 30
seconds, the second program will begin execution. Also, if a user presses a key before the timeout, the second program will begin execution.
To prevent user keystrokes, use the /nobreak
parameter with the TIMEOUT
command. This will ignore any key presses by the user.
However, you can stop the delay by pressing the Ctrl+C, which will raise the errorlevel1
.
Use the PAUSE
Command to Pause the Execution in Batch Script
The PAUSE
command in Batch scripting serves as a mechanism to temporarily halt the execution of a script. It displays the message "Press any key to continue..."
and waits for user input.
This is especially useful when you want to give users an opportunity to review information or confirm an action before proceeding with the script.
The PAUSE
command is simple and does not require any additional parameters or options. It is used as follows:
When the PAUSE
command is encountered in a Batch script, it prompts the user to press any key. Once a key is pressed, the script continues its execution.
The PAUSE
command is used to pause the execution of a Batch file until a key is pressed. It is useful if the user wants to read the output text or wait until a process is finished.
However, there is no timeout, and it will only continue until the user presses a key.
@echo off
echo starting first program.
START /B cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txt
echo The first program is executed successfully.
PAUSE
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script automates the execution of two programs. It starts with testfile1.bat
, captures its output to output.txt
, and confirms successful execution.
The script then prompts the user to press a key to continue. Next, it runs the systeminfo
command and appends its output to output.txt
.
Finally, it opens a new command prompt window for further interaction.
Output:
All the methods mentioned above work fine. If you use the START
command, it is recommended to use /wait
instead of delay commands as the process may take longer than specified.
Use the CALL
Command to Wait for the Command to Finish Execution in Batch Script
The CALL
command in Batch scripting is used to run another Batch file within the current script.
It essentially creates a temporary subroutine, allowing the original script to wait for the called script’s completion before proceeding. This makes it an effective method for synchronizing the execution of commands.
The syntax of the CALL
command is as follows:
CALL :label arguments
CALL [drive:][path]filename [arguments]
:label arguments
: This form is used to call a subroutine within the same Batch file, identified by a label.[drive:][path]filename [arguments]
: This form is used to call an external Batch file by specifying its full path along with any required arguments.
Let’s explore practical examples to demonstrate the use of the CALL
command.
Calling a Subroutine within the Same Batch File
@echo off
echo Starting Process I
CALL :ProcessI
echo Process I completed.
pause
exit
:ProcessI
echo Performing Process I...
:: Add your commands for Process I here
:: For example, "ping -n 5 127.0.0.1" simulates a delay
ping -n 5 127.0.0.1
exit /b
- In this script, we have a main section and a subroutine (
:ProcessI
). - The
CALL :ProcessI
command invokes the subroutine. The execution of the main Batch file will pause until:ProcessI
completes. - The
exit /b
command at the end of:ProcessI
is used to return to the main Batch file after completion.
Output:
Calling an External Batch File
This script uses CALL
to execute an external Batch file named testfile2.bat
located on the desktop.
@echo off
echo Starting Process J
CALL "C:\Users\Username\Desktop\testfile2.bat"
echo Process J completed.
pause
exit
This script automates the execution of an external Batch file, captures its output, and provides feedback along the way. The user is prompted to press a key to continue after the program finishes.
Output:
Use the &&
Operator to Wait for Command to Finish Execution in Batch Script
The &&
operator in Batch scripting allows you to execute commands sequentially, where the second command only runs if the first one succeeds. This creates a dependency between the commands, ensuring that they execute in a specific order.
The syntax of the &&
operator is as follows:
command1
: This is the first command that is executed.command2
: This is the second command that is only executed ifcommand1
succeeds (returns a zero exit code).
Let’s explore practical examples to demonstrate the use of the &&
operator.
Example 1: Running Commands Sequentially
@echo off
echo Starting Process K
echo Performing Process K... && ping -n 5 127.0.0.1
echo Process K completed successfully.
pause
exit
- In this script, the
echo Performing Process K...
command is followed by&&
, which means the next command (ping
) will only execute if the first command is successful. - The
ping
command simulates a delay by waiting for5
seconds (-n 5
) on the local machine (127.0.0.1
). - The script then echoes a message indicating successful completion.
Output:
Example 2: Using Conditional Execution with Batch Files
@echo off
echo Starting Process L
call :ProcessL && (
echo Process L completed successfully.
) || (
echo Process L encountered an error.
)
pause
exit
:ProcessL
echo Performing Process L...
:: Add your commands for Process L here
:: For example, "dir" lists files in the current directory
dir
exit /b
- In this script, the
call :ProcessL
command is followed by&&
. - The subsequent block of code within the
(
and)
is executed only if thecall :ProcessL
succeeds (returns a zero exit code). - If the
call :ProcessL
returns a non-zero exit code, the code after||
is executed instead. - This demonstrates how to conditionally execute different blocks of code based on the success of a preceding command.
Output:
Use a Loop to Wait for Command to Finish Execution in Batch Script
In Batch scripting, a loop is a control structure that allows a set of commands to be executed repeatedly. By utilizing a loop, you can continuously check the status of a process until it completes.
This approach is particularly useful for scenarios where you need to wait for a specific task to finish before proceeding.
Let’s delve into a practical example to demonstrate how to use a loop to wait for a command to complete.
@echo off
echo Starting Process K
echo Performing Process K...
:CheckProcess
tasklist | find /i "process_name.exe" >nul
if %errorlevel% neq 0 (
timeout /t 2 >nul
goto :CheckProcess
)
echo Process K completed successfully.
pause
exit
The Batch script begins with turning off command echoing using @echo off
. It echoes a message indicating the start of a process (Process K
).
Then, the :CheckProcess
label marks the start of a loop. This is where the script checks the status of the target process.
tasklist | find /i "process_name.exe" >nul
retrieves a list of running processes and searches for a process with the specified name (replace process_name.exe
with the actual process name). The >nul
part suppresses the output.
Next, the if %errorlevel% neq 0
checks the return code of the previous command. If it’s not equal to 0
(indicating that the process is still running), the loop continues.
timeout /t 2 >nul
introduces a 2
second delay using the timeout
command. The goto :CheckProcess
redirects the script back to the :CheckProcess
label, effectively creating a loop.
Once the process is no longer found, the script proceeds. Finally, it echoes a message confirming the successful completion of Process K
and waits for user confirmation before exiting.
Output:
Conclusion
This tutorial explores various methods to wait for a command to finish execution in Windows Batch scripting.
- Using
/WAIT
withSTART
: This method ensures the script waits for a command or application to complete using the/WAIT
parameter with theSTART
command. It’s ideal for launching applications that need to finish their tasks. - Introducing Delays with
TIMEOUT
: TheTIMEOUT
command allows for a specified delay in script execution. This is helpful when you want to provide a process with enough time to complete. - Temporary Halt with
PAUSE
: ThePAUSE
command temporarily stops script execution and prompts the user to press a key before continuing. This is useful for user interaction and confirmation. - Using
CALL
for Script Synchronization: TheCALL
command enables the execution of another Batch file within the current script, creating a temporary subroutine. This allows the original script to wait for the called script’s completion. - Conditional Execution with
&&
: The&&
operator ensures that the second command only runs if the first one succeeds, establishing a dependency between commands. This is useful for sequential execution. - Implementing Loops for Continuous Checking: A loop is a control structure that repeatedly checks the status of a process until it completes. This is valuable for scenarios where you need to wait for a specific task to finish.
By understanding these methods, you have gained a comprehensive toolkit for handling command execution and synchronization in Windows Batch scripting. These techniques are invaluable for automating various tasks efficiently.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
When we execute a batch file, the Command Prompt opens and closes automatically after processing the batch file. Sometimes, the command is executed so quickly that it seems like the Command Prompt closes immediately after opening the batch (BAT) file. This prevents users from performing other tasks after the execution of the batch file or viewing the status of the commands they executed in the CMD. If you want the Command prompt window to remain open after processing the batch file, this post may help you.
You can prevent or stop Command Prompt from closing immediately after opening or executing a batch file in the following three ways:
- By using the Pause command.
- By using the cmd /k command.
- By editing the Registry keys.
Let’s see these methods one by one.
1] Prevent Command Prompt from closing immediately by using the Pause command
The Pause command prevents the Command Prompt from closing after processing the batch file.
Follow the steps below:
- Right-click on the batch file and select Edit. This will open the Notepad.
- Type Pause at the end of the command that you have typed in the batch file.
- Save the file.
Now, when you open the batch file, the Command Prompt will not close automatically after processing the file. Instead, it will display a message “Press any key to continue…” When you press any key, the Command Prompt will close.
The Pause command will only let you see how the commands are executed. If you want the Command Prompt to remain open so that you can execute other commands on the same window, you have to use the next method.
Read: Command Prompt keeps crashing
2] Prevent Command Prompt from closing by using the cmd /k command
The cmd /k
command lets you execute new commands after the processing of the batch file without closing the Command Prompt. Right-click on the batch file and type cmd /k
at the end of the batch file. After that, save it.
3] Editing the Registry key to stop Command Prompt from closing
The above two methods stop Command Prompt from closing immediately after processing the batch file. But the only downside of these two methods is you have to use those commands in every batch file. If you already have many batch files, you have to edit all of them.
You can skip editing the batch files by modifying the Registry keys. We have explained the procedure below. Before you proceed, we recommend you create a backup of Registry.
1] Launch the Run command box. Type regedit
and click OK. Click Yes if you get a UAC prompt.
2] In the Registry Editor, navigate to the following paths:
HKEY_CLASSES_ROOT\batfile\shell\open\command HKEY_CLASSES_ROOT\cmdfile\shell\open\command
You will find a “(Default)” value on the right side. Double click on that value and change its Value data to cmd.exe /k "%1" %*
. Click OK to save the changes you made. Close the Registry Editor when you are done.
If after trying the above three methods, the Command prompt is still closing automatically on your system, we suggest you try the following fixes:
- Run SFC scan.
- Troubleshoot in a clean boot state.
- Reset your PC.
1] Run SFC scan
The System File Checker (SFC) is a utility from Microsoft that scans the system files for errors or corruptions and repairs the corrupted files. The issue that you are experiencing may be due to corrupted system files. Hence, running an SFC scan may fix the problem.
2] Troubleshoot in a clean boot state
Sometimes, a faulty program creates several issues on a Windows PC. You can identify the faulty program or software by troubleshooting in a clean boot state. If you find a program the culprit of the problem, consider uninstalling it.
3] Reset your PC
If nothing helps you fix the error, consider resetting your PC.
Hope this helps.
How do I run an EXE from Command Prompt?
To run an EXE from Command Prompt, follow the steps below:
1] Launch the Command Prompt.
2] Type cd "file path"
without quotations and hit Enter. The file path is the installation location of the EXE file. To know the file location, right-click on the shortcut icon of the program that you want to open via CMD and select Open file location. Now, click on the address bar of the File Explorer and copy the entire path. You can paste this entire path directly in the Command Prompt by using the Ctrl + V keys.
3] Now, type start "filename.exe"
without quotations and press Enter.
This will launch the EXE file.
How do I keep a command window open in a batch file?
You can use either Pause or cmd /k commands to keep the command window open in a batch file. If you want, you can also make this action permanent by modifying some keys in the Registry. We have explained all these three methods above in this article.
Related: Command Prompt cmd.exe keeps popping up on Startup.
Download Article
Download Article
If you need some extra time for a command in your batch file to execute, there are several easy ways to delay a batch file. While the well-known sleep command from older versions of Windows is not available in Windows 10 or 11, you can use the timeout, pause, ping, and choice commands to wait a specific number of seconds or simply pause until the user presses a key. This wikiHow article will teach you 5 simple ways to delay the next command in your batch file on any version of Windows.
Things You Should Know
- The timeout command lets you pause for specific number of seconds, until a user presses a key, or indefinitely.
- Use the pause command to delay the batch file until a user presses any key, or the choice command to give the user options to choose from.
- You can hide on-screen messages that indicate delay to the user by adding >nul to the end of the timeout, ping, and choice commands.
-
By inserting the timeout command into your batch file, you can prompt the batch file to wait a specified number of seconds (or for a key press) before proceeding.[1]
This command is available on all modern versions of windows, including Windows 10.-
timeout /t <timeoutinseconds> [/nobreak].[2]
- To pause for 30 seconds and prevent the user from interrupting the pause with a keystroke, you’d enter timeout /t 30 /nobreak.[3]
- The user will see Waiting for 30 seconds, press CTRL+C to quit …
- To delay 100 seconds and allow the user to interrupt the delay, you’d use timeout /t 100.
- The user will see Waiting for 100 seconds, press a key to continue …
- To delay indefinitely until a user enters a keystroke, use timeout /t -1.
- The user will see Press any key to continue …
- If you don’t want to display a message to the user during the delay, add >nul to the end of your timeout command.
-
timeout /t <timeoutinseconds> [/nobreak].[2]
Advertisement
-
This simple command doesn’t require any flags and you can place it anywhere in your script to prevent further action. When the pause command runs in the batch file, the user will see Press any key to continue . . . on a new line. When the user presses a key, the script continues.[4]
- You might use pause right before a section of the batch file that you might not want to process, or before providing instructions to the user to insert a disk before continuing.[5]
- At the pause, you can stop the batch program completely by pressing Ctrl + C and then Y.
- You might use pause right before a section of the batch file that you might not want to process, or before providing instructions to the user to insert a disk before continuing.[5]
-
You can add a ping anywhere in your batch file, enter any hostname or IP address (including a nonexistent address), and specify the time in milliseconds to delay the next command. You’ll also be able to hide the output of the ping so the user won’t see what’s happening in the background.[6]
-
ping /n 1 /w <timeout in milliseconds> localhost >nul
- Ping has many more available flags, but for the purpose of delaying a batch file, you’ll only need to use a few. In this case, we’ll ping ourselves by using localhost as our destination.
- To pause quietly for 10 seconds, you’d use ping /n 1 /w 10000 localhost >nul
-
ping /n 1 /w <timeout in milliseconds> localhost >nul
Advertisement
-
You can customize the list of choices, use the default options of Y or N, or choose not to display any choices at all and simply delay your script for a specific period of time.[7]
-
choice [/c [<choice1><choice2><…>]] [/n] [/cs] [/t <seconds> /d <choice>] [/m <text>]
- /c <choice1><choice2><…>: Specifies the choices you’d like to create, which can include a-z, A-Z, 0-9, and ASCII characters 128-254.
- /t <seconds>: Use this flag to specify how many seconds to wait before the default choice is selected. You can set this value to any number between 0 (which instantly selects the default choice) and 9999.
- /d <choice>: Specifies the default choice from the list of choices created with /c.
- /n (optional): hides the list of choices, but still allows the user to select one.
- /m <text> (optional): displays a message before the choice list. If you don’t include this flag but don’t hide the choice list, the choices will still be displayed.
- /cs (optional): This specifies that choices are case-sensitive, which is important if you want to assign different functions to capital and lowercase letters.
- To create a delay with CHOICE without displaying a message or forcing the user to choose something, use rem | choice /c:AB /T:A,30 >nul. This command simply delays the batch file for 30 seconds (similar to using Timeout with no message), provides no choices to the user, and continues after the delay. You can replace 30 with any value up to 9999 (in seconds).
-
choice [/c [<choice1><choice2><…>]] [/n] [/cs] [/t <seconds> /d <choice>] [/m <text>]
-
If you’re using Windows XP or earlier, you can use sleep to specify a wait time in seconds. This command will not work in any newer versions of Windows starting with Windows Vista, but is the easiest way to add wait time to batch files running on older systems.
- sleep <seconds>
- The sleep command only requires the number of seconds you want to delay the batch file. For example, to wait 30 seconds before continuing, you’d use sleep 30.
Advertisement
Add New Question
-
Question
How do I not get a message when I use timeout?
Add the >nul qualifier, like this: timeout /t 120 >nul. This causes a 2 minute delay with no output to the screen.
-
Question
What if the sleep command doesn’t work?
If the sleep command doesn’t work, use timeout instead.
-
Question
What if I want to wait less than one second? I can’t just use a dot or a comma.
You can use the ping command. This command, if used with a non-existent IP address, will try to talk to a non-existent computer and give up after a specified number of milliseconds. Just multiply the number of seconds by 1000, and you’re good to go.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can run a batch file on any Windows computer by double-clicking it, or launch it from the command prompt.
-
The «PAUSE» command is best used in situations where you’re relying on a user to trigger the next section of the batch file, while the «TIMEOUT» command is suited to situations in which you want to allow the file to run automatically.
-
The formerly used «SLEEP» command does not work on Windows Vista or later, including Windows 10 and 11.
Thanks for submitting a tip for review!
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 1,609,005 times.