What Is a BAT File?
A BAT (Batch) file is a script file executed in the Windows Command Prompt (CMD). Saved with the .bat or .cmd extension, it runs multiple commands sequentially and automatically. It is widely used for task automation, environment configuration, deployment scripts, and more.
This article covers BAT file basic syntax, variables, conditionals, loops, and practical automation scripts.
Basic Syntax
The first line of a BAT file typically starts with @echo off. This command prevents subsequent commands from being displayed on screen.
@echo off
REM This line is a comment
echo Hello, this is a BAT script!
echo Current date: %date%
echo Current time: %time%
pause
pause displays “Press any key to continue…” and waits for user input. It’s useful for reviewing script execution results.
| Command | Description | Example |
|---|---|---|
@echo off | Disable command display | Used on the first line |
echo | Print message | echo Hello |
REM | Comment | REM description text |
pause | Wait for user input | For viewing results |
cls | Clear screen | Reset output |
exit | End script | exit /b 0 (success code) |
Variables and Parameters
In BAT, variables are declared with the set command and referenced with %variablename%. Arguments passed during script execution are accessed with %1, %2, etc.
@echo off
REM Variable declaration and usage
set PROJECT_NAME=MyApp
set VERSION=1.0.0
echo Project: %PROJECT_NAME% v%VERSION%
REM Get user input
set /p USER_NAME=Enter your name:
echo Hello, %USER_NAME%!
REM Arithmetic operations (/a option)
set /a RESULT=10+20
echo 10 + 20 = %RESULT%
REM Parameter usage (script.bat arg1 arg2)
echo First argument: %1
echo Second argument: %2
echo All arguments: %*
set /p reads user input into a variable, and set /a performs arithmetic operations. Parameter %0 is the path of the script itself.
Conditionals and Loops
Use if for conditional branching and for for loops.
@echo off
REM === Conditionals ===
set /a NUM=15
REM Numeric comparison: EQU(==), NEQ(!=), LSS(<), LEQ(<=), GTR(>), GEQ(>=)
if %NUM% GEQ 10 (
echo %NUM% is 10 or greater
) else (
echo %NUM% is less than 10
)
REM Check file existence
if exist "config.ini" (
echo Config file found
) else (
echo Config file not found. Creating defaults
echo [default] > config.ini
)
REM === Loops ===
REM Iterate over files
echo === .txt files in current folder ===
for %%f in (*.txt) do (
echo File: %%f
)
REM Numeric range loop (1 to 5)
for /l %%i in (1,1,5) do (
echo Count: %%i
)
BAT comparison operators differ from programming languages. Instead of ==, use EQU; instead of <, use LSS, etc. In for loops, use %% inside BAT files and % when typing directly in CMD.
| Comparison Operator | Meaning | Programming Equivalent |
|---|---|---|
EQU | Equal | == |
NEQ | Not equal | != |
LSS | Less than | < |
LEQ | Less than or equal | <= |
GTR | Greater than | > |
GEQ | Greater than or equal | >= |
Practical Script: Project Build Automation
A build and deployment automation script commonly used in practice.
@echo off
setlocal enabledelayedexpansion
REM === Project Build & Deploy Script ===
set PROJECT_DIR=%~dp0
set BUILD_DIR=%PROJECT_DIR%dist
set LOG_FILE=%PROJECT_DIR%build.log
echo [%date% %time%] Build started > "%LOG_FILE%"
REM 1. Clean previous build
if exist "%BUILD_DIR%" (
echo Deleting previous build folder...
rmdir /s /q "%BUILD_DIR%"
)
mkdir "%BUILD_DIR%"
REM 2. Run build
echo Running build...
call npm run build >> "%LOG_FILE%" 2>&1
if %ERRORLEVEL% NEQ 0 (
echo [Error] Build failed! Check the log: %LOG_FILE%
exit /b 1
)
REM 3. Verify results
for /f %%a in ('dir /s /b "%BUILD_DIR%\*" ^| find /c /v ""') do set FILE_COUNT=%%a
echo Build complete! Files generated: !FILE_COUNT!
echo [%date% %time%] Build complete (%FILE_COUNT% files) >> "%LOG_FILE%"
endlocal
pause
setlocal enabledelayedexpansion enables delayed variable expansion using the !variable! syntax. This is essential when variable values change inside loops. %ERRORLEVEL% is the exit code of the previous command — non-zero indicates an error.
Considerations and Tips
Paths with spaces require quotes: cd "C:\Program Files\MyApp" — without quotes, the path gets truncated and causes errors.
Use call to invoke other BAT files: Using call other.bat returns control to the current script. Without call, the current script terminates.
Encoding: To display non-ASCII characters, set the UTF-8 code page with chcp 65001.
Summary
BAT scripting is the oldest and most universal automation tool in the Windows environment. Key takeaways:
- Start with
@echo off, declare variables withset, reference with%variable% - Conditionals use
if ... ( ) else ( ), comparisons useEQU/NEQ/GTRabbreviations - Loops use
for— file iteration, numeric range (/l), command output parsing (/f) - Error handling with
%ERRORLEVEL%, call other scripts withcall - For complex logic, consider switching to PowerShell (PS1)