Ora

How to Repeat a Command in Command Prompt?

Published in Command Line Automation 6 mins read

Repeating commands in Command Prompt can be achieved through various methods, from simply recalling previous entries to executing complex loops or automated scripts. The most efficient way to repeat the last command is typically by using the arrow keys, while more advanced repetition involves using FOR loops, batch files, or in specific cases, specialized utilities.

Recalling Previous Commands (Standard Repetition)

For re-executing a command you've recently typed, Command Prompt offers built-in history features:

  • Up Arrow Key (↑): Pressing the Up Arrow key cycles backward through your command history, displaying previous commands one by one. You can press Enter to execute the selected command.
  • Down Arrow Key (↓): Pressing the Down Arrow key cycles forward through your command history.
  • F7 Key: Opens a small window displaying a numbered list of recent commands. You can navigate this list with the arrow keys and press Enter to execute the chosen command. This is particularly useful for quickly finding a command further back in your history.
  • F8 Key: Cycles through commands that match the characters currently typed on the command line. If you type dir and then press F8, it will show previous dir commands.
  • F9 Key: Allows you to execute a command by its number from the F7 history list. Press F9, enter the command number, and press Enter.

For more extensive history management or creating custom shortcuts, the DOSKEY command is invaluable:

  • doskey /history: Displays a complete list of all commands stored in the current session's buffer.
  • doskey /macros: Shows any custom command macros you've defined. You can create macros for frequently used commands with doskey macro_name=command(s). For example, doskey ll=dir /b creates a macro ll to list files in bare format.

Repeating Commands Multiple Times (Using FOR Loops)

When you need to execute a command multiple times, potentially with varying parameters, FOR loops are the most powerful and flexible solution within Command Prompt. They are widely used in batch scripting for automation.

Common FOR Loop Types:

  1. Iterating a Numerical Range (FOR /L):
    This loop is ideal for running a command a specific number of times or iterating through a sequence of numbers.

    FOR /L %i IN (start,step,end) DO command
    • %i: A loop variable (use %%i in batch files).
    • start: The starting number.
    • step: The increment between numbers.
    • end: The ending number.
    • command: The command to execute, often using %i as a parameter.

    Example: Echo "Hello" five times.

    FOR /L %i IN (1,1,5) DO echo Hello %i
  2. Iterating Through a Set of Items (FOR):
    This loop processes items in a list, files in a directory, or specific strings.

    FOR %i IN (item1 item2 item3) DO command

    Example: Ping multiple servers.

    FOR %s IN (server1 server2 server3) DO ping %s
  3. Iterating Through Files in a Directory (FOR /F or FOR with wildcards):
    You can process each file matching a pattern.

    FOR %f IN (*.txt) DO echo Processing file: %f

    For more advanced file processing (e.g., reading lines from a file, parsing command output), FOR /F is used.

    FOR /F "tokens=*" %l IN ('type mylog.txt') DO echo Line: %l

Repeating a Command Indefinitely or with a Specific Stop

While standard Command Prompt doesn't have a direct Repeat command to indefinitely execute and then stop with Esc, some specific utilities or environments might offer such a feature.

A specific way to repeat a command (as found in certain systems or tools):
If you have access to a utility or environment that supports a command like Repeat (which is not a standard feature of the native Windows Command Prompt CMD.exe), you would typically follow these steps:

  1. Type Repeat at the command prompt.
  2. Type the command you wish to repeat immediately after Repeat or on the next line, depending on the specific tool's syntax.
  3. The command would then repeat, potentially prompting you for input or displaying output as necessary.
  4. To stop the repetition, you would press the Esc key.

However, it's crucial to understand that a direct Repeat command as described above is not a standard, built-in feature of the native Windows Command Prompt (CMD.exe). For indefinite or conditional repetition in CMD, you need to use batch scripting.

Standard CMD Alternatives for Indefinite Repetition:

To achieve continuous execution in a standard Command Prompt environment, you typically create a simple batch file:

  1. Using a GOTO loop in a batch file:
    Create a text file (e.g., infinite_command.bat) and add the following:

    @echo off
    :loop
    your_command_here
    timeout /t 5 >nul  REM Optional: Wait 5 seconds before repeating
    goto loop
    • Replace your_command_here with the command you want to repeat.
    • The timeout /t 5 >nul line introduces a 5-second delay. Remove or adjust the number as needed. >nul suppresses the countdown message.
    • To stop this loop, you typically need to close the command prompt window or press Ctrl+C multiple times.
  2. Using CALL for recursive calls (less common for indefinite loops):
    You can also use CALL within a batch file to call itself, though this can lead to stack overflow if not properly managed or if the loop is truly indefinite without exit conditions. It's generally better for tasks where a finite number of nested calls is expected.

Using Batch Files for Repetitive Tasks

For any task that requires repeating multiple commands, using parameters, or implementing complex logic, batch files (.bat or .cmd) are the go-to solution. They allow you to:

  • Store sequences of commands.
  • Use variables and parameters (%1, %2, etc.).
  • Implement conditional logic (IF statements).
  • Create loops (FOR, GOTO).

Example: A Simple Batch File (backup.bat)

@echo off
echo Starting backup process...
robocopy C:\Source D:\Backup /MIR /NDL /NFL /NJH /NJS /FP /NS /NC /NP /R:1 /W:1
echo Backup completed.
pause

You can simply type backup.bat at the command prompt to execute all commands within it.

Summary of Command Repetition Methods

Method Use Case Execution Control
Arrow Keys / F7/F8/F9 Recall and re-execute recent commands Interactive Select, then Enter
DOSKEY Macros Shorten frequently used commands Interactive / Batch file Type macro name, then Enter
FOR Loops Execute commands multiple times (fixed/varied) Interactive / Batch file Loop conditions define repetition; Ctrl+C to interrupt
Batch Files (with GOTO) Indefinite or complex conditional repetition Batch file execution Ctrl+C to interrupt; programmatically exit conditions within the script
Repeat Command (Specific Environments) Indefinite repetition in specific tools Interactive (if available in your shell/utility) Esc to stop (as per specific tool's documentation)

By leveraging these methods, you can efficiently repeat commands and automate tasks in the Command Prompt environment.