How can I pass arguments to a batch file?

To pass arguments to a batch file in Windows, you can provide them after the script name when executing it. The batch script then accesses these arguments using %1, %2, %3, etc. Here’s a detailed guide with examples:

1. Basic Syntax

When calling the batch file, list arguments after the script name:

my_script.bat arg1 arg2 "arg with spaces"

Inside the batch file:

  • %1: First argument (arg1).
  • %2: Second argument (arg2).
  • %*: All arguments (arg1 arg2 "arg with spaces").
  • %0: Name of the batch file itself (my_script.bat).

2. Accessing Arguments in a Batch File

Example 1: Display Arguments

@echo off
echo First argument: %1
echo Second argument: %2
echo All arguments: %*

Output when run as my_script.bat Hello World:

First argument: Hello
Second argument: World
All arguments: Hello World

3. Handling Spaces in Arguments

Enclose arguments with spaces in quotes:

my_script.bat "First Name" "Last Name"

Batch file:

@echo off
echo Full Name: %1 %2  // Output: Full Name: "First Name" "Last Name"

To remove quotes from arguments, use %~ modifiers:

@echo off
echo Full Name: %~1 %~2  // Output: Full Name: First Name Last Name

4. Checking If Arguments Exist

Example 2: Validate Required Arguments

@echo off
if "%1"=="" (
    echo Error: No arguments provided.
    exit /b
)
echo First argument: %1

5. Looping Through All Arguments

Example 3: Process Each Argument

@echo off
echo Arguments:
for %%a in (%*) do (
    echo - %%a
)

Output for my_script.bat A B "C D":

Arguments:
- A
- B
- C D

6. Advanced: Using SHIFT for More Than 9 Arguments

Batch files only directly access %1 to %9. Use SHIFT to handle more:

@echo off
:loop
if "%1"=="" exit /b
echo Argument: %1
SHIFT
goto loop

This loops through all arguments (even beyond 9).

7. Common Use Cases

Example 4: Copy Files with Arguments

@echo off
copy %1 %2
echo Copied %1 to %2

Run as:

my_script.bat "C:\file.txt" "D:\backup\"

Example 5: Launch Programs with Parameters

@echo off
start "" "C:\Program Files\App\app.exe" %*

Run as:

launch.bat -mode=debug -log

Key Notes

  • Case Sensitivity: Batch arguments are not case-sensitive.
  • Quotes: Use " to group arguments with spaces.
  • Modifiers:
  • %~1: Remove surrounding quotes from %1.
  • %~f1: Expand %1 to a full path.
  • Full list: for /? in Command Prompt.

Summary

  • Pass arguments after the batch filename: script.bat arg1 arg2.
  • Use %1 to %9 to access arguments, or %* for all.
  • Handle spaces with quotes and use %~ to strip them.
  • Validate arguments with if "%1"=="" before using them.

Leave a Reply

Your email address will not be published. Required fields are marked *