-
ECHOis your primary debugging tool in batch. You can print variables, track flow, and show command results in real time.@ECHO OFF SET USERNAME=omkar :: Debug message ECHO The username is: %USERNAME% :: Debug current directory ECHO Current directory: %CD%
Technique Example Print values ECHO %var%Show where script is running ECHO Running step 1...Debug file paths or arguments ECHO Copying to %targetPath%Combine with PAUSEto inspectECHO DEBUG && PAUSE
@ECHO OFF ECHO [DEBUG] Starting script SET FILE=report.txt ECHO [DEBUG] File to process: %FILE% IF EXIST %FILE% ( ECHO [DEBUG] File exists. Proceeding... ) ELSE ( ECHO [ERROR] File not found: %FILE% )
-
Batch expands variables when the line is read, which can cause issues inside loops or
IFblocks.SET COUNT=0 FOR %%I IN (*.txt) DO ( SET /A COUNT+=1 ECHO File: %%I - Count: %COUNT% )
This won't work, because
%COUNT%is expanded before the loop starts.@ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION SET COUNT=0 FOR %%I IN (*.txt) DO ( SET /A COUNT+=1 ECHO File: %%I - Count: !COUNT! ) ENDLOCAL
🔄
!COUNT!uses delayed expansion — updated at runtime inside loops.
SET VAR=Test ECHO Without delayed: %VAR% SETLOCAL ENABLEDELAYEDEXPANSION ECHO With delayed: !VAR! ENDLOCAL
-
Batch scripts don’t throw exceptions, but you can catch issues using:
%ERRORLEVEL%IF ERRORLEVEL||and&&operators
COPY file.txt D:\backup\ IF ERRORLEVEL 1 ( ECHO [ERROR] Copy failed! ) ELSE ( ECHO [INFO] Copy successful. )
XCOPY C:\Data D:\Backup /E /I || ECHO [ERROR] Backup failed!
CALL :DoTask IF ERRORLEVEL 1 ( ECHO [ERROR] Task failed! EXIT /B 1 ) GOTO :EOF :DoTask REM Simulate failure EXIT /B 1
| Tip | Why It's Useful |
|---|---|
ECHO ON at top temporarily |
Shows every command as it runs |
Use PAUSE before/after critical steps |
Waits for user input to inspect |
ECHO %ERRORLEVEL% after commands |
View exact exit codes |
Use temporary LOG files |
Save all output for post-run analysis |
| Modularize code into subroutines | Easier to isolate and test parts |
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET LOG=script.log
CALL :Log "[INFO] Script started"
SET FILE=data.txt
IF EXIST %FILE% (
CALL :Log "[INFO] Found file: %FILE%"
) ELSE (
CALL :Log "[ERROR] Missing file: %FILE%"
EXIT /B 1
)
:: Simulated task
DIR > NUL 2>&1 || CALL :Log "[ERROR] DIR failed"
CALL :Log "[INFO] Script completed"
ENDLOCAL
GOTO :EOF
:Log
ECHO [%DATE% %TIME%] %~1 >> %LOG%
EXIT /B| Feature | Tool / Method | Use Case |
|---|---|---|
| Debug print | ECHO |
Show variables and flow |
| Pause script temporarily | PAUSE |
Manual inspection during dev |
| Error detection | IF ERRORLEVEL, |
Respond to failures |
| Variable accuracy | !VAR! (delayed) |
Inside loops or conditional blocks |
| Modular logging | :Log subroutine |
Consistent debug messages |