Batch Files
Coding Tips
Script Arguments
Windows Command Line
Programming

How can I pass arguments to a batch file?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Batch files accept arguments through positional parameters %1 through %9. When you run myscript.bat hello world, %1 is hello and %2 is world. The special variable %0 holds the script's own filename, and %* expands to all arguments as a single string. For more than nine arguments, use the SHIFT command to rotate parameters left.

Basic Positional Parameters

Arguments are passed on the command line separated by spaces and accessed inside the batch file using %1, %2, through %9.

batch
1@echo off
2echo First argument: %1
3echo Second argument: %2
4echo Third argument: %3

Running it:

cmd
greet.bat Alice Bob Charlie

Output:

 
First argument: Alice
Second argument: Bob
Third argument: Charlie

If fewer arguments are provided than referenced, the missing parameters expand to empty strings. %4 in the example above would expand to nothing.

The %0 and %* Special Variables

%0 is the name (or full path) of the batch file itself. %* represents all arguments combined.

batch
@echo off
echo Script name: %0
echo All arguments: %*

Running deploy.bat staging us-east-1 verbose produces:

 
Script name: deploy.bat
All arguments: staging us-east-1 verbose

%* is particularly useful when passing all arguments to another command:

batch
@echo off
REM Forward all arguments to a Python script
python main.py %*

Handling Arguments with Spaces

Arguments containing spaces must be wrapped in double quotes on the command line:

cmd
copy_file.bat "C:\Users\John Smith\report.txt" "D:\Backup"

Inside the batch file, %1 includes the quotes: "C:\Users\John Smith\report.txt". To strip the quotes, use the ~ modifier:

batch
@echo off
echo With quotes: %1
echo Without quotes: %~1

Output:

 
With quotes: "C:\Users\John Smith\report.txt"
Without quotes: C:\Users\John Smith\report.txt

Parameter Modifiers

The %~ syntax provides powerful modifiers for extracting parts of file paths:

ModifierExpands toExample (if %1 is "C:\src\app.exe")
%~1Removes surrounding quotesC:\src\app.exe
%~f1Full pathC:\src\app.exe
%~d1Drive letter onlyC:
%~p1Path only (no drive, no filename)\src\
%~n1Filename without extensionapp
%~x1Extension only.exe
%~dp1Drive + pathC:\src\
%~nx1Filename + extensionapp.exe
%~z1File size in bytes45056
%~t1Timestamp of file06/18/2026 10:30 AM

These modifiers work for any parameter, not just file paths, though the path-specific modifiers only produce meaningful results when the argument is actually a valid file path.

Validating Arguments

Always check whether required arguments were provided before using them:

batch
1@echo off
2if "%~1"=="" (
3    echo Usage: deploy.bat [environment] [region]
4    echo Example: deploy.bat staging us-east-1
5    exit /b 1
6)
7
8if "%~2"=="" (
9    echo Error: Region is required.
10    exit /b 1
11)
12
13set ENVIRONMENT=%~1
14set REGION=%~2
15
16echo Deploying to %ENVIRONMENT% in %REGION%...

Using %~1 (with tilde) inside the if comparison strips quotes, preventing syntax errors when arguments contain spaces.

Using SHIFT for More Than Nine Arguments

The SHIFT command moves all parameters one position to the left: %2 becomes %1, %3 becomes %2, and so on. The original %1 is discarded.

batch
1@echo off
2echo Processing all arguments:
3
4:loop
5if "%~1"=="" goto done
6echo - %1
7shift
8goto loop
9
10:done
11echo Finished.

Running process.bat alpha beta gamma delta outputs:

 
1Processing all arguments:
2- alpha
3- beta
4- gamma
5- delta
6Finished.

This pattern is essential for batch files that accept a variable number of arguments.

Named Parameters with Flags

Batch files do not have built-in named parameter support, but you can implement it with a parsing loop:

batch
1@echo off
2setlocal
3
4set "SERVER="
5set "PORT=8080"
6set "VERBOSE=false"
7
8:parse
9if "%~1"=="" goto main
10
11if /i "%~1"=="--server" (
12    set "SERVER=%~2"
13    shift
14    shift
15    goto parse
16)
17if /i "%~1"=="--port" (
18    set "PORT=%~2"
19    shift
20    shift
21    goto parse
22)
23if /i "%~1"=="--verbose" (
24    set "VERBOSE=true"
25    shift
26    goto parse
27)
28
29echo Unknown argument: %1
30exit /b 1
31
32:main
33if "%SERVER%"=="" (
34    echo Error: --server is required
35    exit /b 1
36)
37
38echo Connecting to %SERVER%:%PORT%
39if "%VERBOSE%"=="true" echo Verbose mode enabled

Usage:

cmd
connect.bat --server db.example.com --port 5432 --verbose

Practical Example: Build and Deploy Script

Here is a realistic batch file that uses argument handling for a deployment workflow:

batch
1@echo off
2setlocal enabledelayedexpansion
3
4REM Usage: deploy.bat [build|deploy|both] [environment] [--skip-tests]
5set ACTION=%~1
6set ENV=%~2
7set SKIP_TESTS=false
8
9if /i "%~3"=="--skip-tests" set SKIP_TESTS=true
10
11if "%ACTION%"=="" (
12    echo Usage: deploy.bat [build^|deploy^|both] [environment] [--skip-tests]
13    exit /b 1
14)
15
16if "%ENV%"=="" (
17    echo Error: Environment is required (staging, production)
18    exit /b 1
19)
20
21if /i "%ACTION%"=="build" goto build
22if /i "%ACTION%"=="deploy" goto deploy
23if /i "%ACTION%"=="both" goto build
24echo Unknown action: %ACTION%
25exit /b 1
26
27:build
28echo Building for %ENV%...
29if "%SKIP_TESTS%"=="false" (
30    echo Running tests...
31    call npm test
32    if errorlevel 1 (
33        echo Tests failed. Aborting.
34        exit /b 1
35    )
36)
37call npm run build
38if /i "%ACTION%"=="both" goto deploy
39goto end
40
41:deploy
42echo Deploying to %ENV%...
43if /i "%ENV%"=="production" (
44    echo WARNING: Deploying to production.
45    set /p CONFIRM="Continue? (y/n): "
46    if /i not "!CONFIRM!"=="y" (
47        echo Aborted.
48        exit /b 0
49    )
50)
51echo Deployment complete.
52goto end
53
54:end
55echo Done.

Batch Arguments vs. PowerShell Parameters

FeatureBatch (%1)PowerShell (param())
Positional parameters%1 through %9$args[0], $args[1], ...
Named parametersManual parsing requiredBuilt-in with param() block
Type validationNoneSupports [string], [int], etc.
Default valuesManual (if "%~1"=="" set ...)param($Name = "default")
More than 9 argsRequires SHIFTUnlimited via $args array
Quote handling%~1 strips quotesAutomatic
Tab completionNoneBuilt-in for named params

For new scripts, PowerShell is almost always the better choice. Batch files are relevant when you need compatibility with systems that do not have PowerShell installed or when maintaining legacy scripts.

Common Pitfalls

Not quoting %1 in if comparisons. If %1 is empty, if %1=="" ... becomes if =="" ..., which is a syntax error. Always use if "%~1"=="" with both tilde (to strip outer quotes) and surrounding quotes (to handle empty values).

Forgetting setlocal in scripts that set variables. Without setlocal, variables set inside the batch file leak into the calling shell session. This can cause confusing behavior when running the script multiple times. Always start with setlocal.

Using %VAR% inside a parenthesized block. Variable expansion happens when the block is parsed, not when each line executes. Inside if or for blocks, use !VAR! with setlocal enabledelayedexpansion:

batch
1@echo off
2setlocal enabledelayedexpansion
3set COUNT=0
4for %%f in (*.txt) do (
5    set /a COUNT+=1
6    echo File !COUNT!: %%f
7)

Confusing exit with exit /b. Using exit without /b closes the entire command prompt window. Use exit /b [errorlevel] to return from the batch file while keeping the parent shell open.

Passing arguments with special characters. Characters like &, |, <, >, and ^ have special meaning in CMD. Arguments containing these must be escaped or quoted:

cmd
1REM This breaks:
2myscript.bat hello & world
3
4REM This works:
5myscript.bat "hello & world"

Summary

Batch files receive arguments through %1 to %9 for positional access, %* for all arguments combined, and %0 for the script name. Use %~1 to strip surrounding quotes and %~dp1 and similar modifiers to extract path components. Validate arguments early with if "%~1"=="" checks. For more than nine arguments, loop with SHIFT. For named flag-style parameters, implement a parsing loop with if /i comparisons. Always use setlocal to prevent variable leakage and exit /b instead of bare exit to avoid closing the calling shell.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.