How to Validate Command-Line Arguments in Batch Script
User input is the most unpredictable part of any script. If a user provides a file path that doesn't exist, a folder name that is actually a file, or a number where a string was expected, your Batch script might crash or, worse, delete the wrong data. Validating command-line arguments (parameters) is the "Armor" of your code, ensuring that your logic only executes when the inputs are safe and correct.
This guide will explain how to implement robust validation for presence, file existence, and specific values in a Batch script.
1. Checking for Missing Arguments
The most basic validation is ensuring that the user actually provided the necessary data.
@echo off
:: Check if %1 (the first argument) is empty
if "%~1"=="" (
echo [ERROR] No input file specified.
echo Usage: %~nx0 [InputFile.txt]
pause
exit /b 1
)
echo [OK] Argument received: %~1
Using "%~1" is a best practice. The tilde ~ removes any quotes the user might have included, and the outer quotes ensure that empty strings don't crash the IF statement.
2. Validating File and Directory Existence
If your script processes files, you must verify they exist before running commands like copy or del.
@echo off
set "filepath=%~1"
:: First check if any argument was provided
if "%filepath%"=="" (
echo [ERROR] No path specified.
echo Usage: %~nx0 [FilePath]
exit /b 1
)
:: Check if the path exists at all
if not exist "%filepath%" (
echo [ERROR] Path not found: "%filepath%"
exit /b 1
)
:: Check if the path is a directory instead of a file
if exist "%filepath%\" (
echo [ERROR] "%filepath%" is a directory, not a file.
echo Please provide a path to a file.
exit /b 1
)
echo [OK] File validated: "%filepath%"
echo Proceeding with processing...
3. Validating Options (Choice Lists)
If your script accepts a "Flag" (like /COPY or /MOVE), you should ensure the user didn't make a typo.
@echo off
set "action=%~1"
:: Check if any argument was provided
if "%action%"=="" (
echo [ERROR] No action specified.
echo Usage: %~nx0 [BUILD ^| CLEAN]
exit /b 1
)
:: Use /I for case-insensitive comparison
if /i "%action%"=="BUILD" goto :do_build
if /i "%action%"=="CLEAN" goto :do_clean
:: If we reached here, the option was invalid
echo [ERROR] Invalid action: "%action%"
echo Valid options are: BUILD, CLEAN
exit /b 1
:do_build
echo [ACTION] Running build process...
:: Build logic here
exit /b 0
:do_clean
echo [ACTION] Running clean process...
:: Clean logic here
exit /b 0
4. Validating Numeric Input
Batch handles everything as a string, but you can test whether an argument is a valid number by checking if it survives a math operation unchanged.
@echo off
setlocal
set "input=%~1"
:: Check if any argument was provided
if "%input%"=="" (
echo [ERROR] No number specified.
echo Usage: %~nx0 [number]
exit /b 1
)
:: Attempt a math assignment, set /a treats non-numeric strings as 0
set /a "test=%input%" 2>nul
:: Verify the result matches the original input
:: This catches cases where set /a silently converts "abc" to 0
if not "%test%"=="%input%" (
echo [ERROR] "%input%" is not a valid integer.
exit /b 1
)
echo [OK] Valid number received: %input%
endlocal
Why compare %test% to %input%?
The set /a command does not set %errorlevel% to non-zero for invalid input. Instead, it silently converts non-numeric strings to 0. By comparing the result back to the original, we detect this silent conversion: if the user entered abc, set /a produces 0, and "0" does not equal "abc", so validation fails correctly.
How to Avoid Common Errors
Wrong Way: Case-Sensitive Checks
By default, IF "%1"=="YES" will fail if the user types yes.
Correct Way: Always use the /i switch in your IF statements to make comparisons case-insensitive.
Problem: Filenames with Spaces
If a user passes C:\My Documents\file.txt without quotes, Batch will treat it as two separate arguments (%1 and %2).
Solution: Always tell your users to wrap paths in double quotes, and always use "%~1" inside your script to handle them safely.
Best Practices and Rules
1. The "Usage" Block
Always include a clear usage example in your validation error. This helps the user correct their mistake immediately without having to open the script code.
2. Exit Codes
When validation fails, exit with a non-zero code (exit /b 1). This allows other scripts or scheduled tasks to know that your script didn't finish its job properly.
3. Order of Operations
Validate your arguments at the very top of the script, before you create folders, delete logs, or start background services. This follows the "Fail Early" principle of software development.
Conclusions
Validating command-line arguments transforms a "fragile" Batch script into a professional tool. By checking for presence, verifying file paths, and filtering for specific options, you prevent your logic from acting on bad data. This layer of security is essential for any automation that interacts with the file system or crucial system settings, ensuring that your scripts are both safe and user-friendly.