Batch Debugging Techniques

Introduction

Batch gives you almost no built-in debugging tools, so you must debug using echo statements, delayed expansion checks, errorlevel tracking, and command tracing. These techniques help you find bugs fast in .bat scripts.

1. Enable Command Tracing

Show every executed command:

@echo on
    

Turn off later with:

@echo off
    

2. Use echo Checkpoints

echo Step 1 OK
echo Current value: %var%
echo Loop reached
    

Place them inside loops and conditions to see where code breaks.

3. Check Error Codes (errorlevel)

somecommand
echo Error code: %errorlevel%
    

Errorlevel helps you detect failures from external commands.

4. Test Conditions With dummy commands

if "%var%"=="" echo VAR EMPTY
if "%var%"=="abc" echo match
    

5. Debug Delayed Expansion Issues

Print both normal and delayed variables:

echo normal: %count%
echo delayed: !count!
    

6. Pause Script Execution

pause
pause >nul
    

Useful for reading output before window closes.

7. Use set to Dump All Variables

set
set var
    

8. Print Values Inside Loops

for %%i in (*) do (
  echo Loop: %%i
)
    

9. Debug Path Issues

where python
where node
echo %PATH%
    

10. Check Quoting Problems

echo "%filename%"
echo [%filename%]
    

11. Use > debug.log

yourscript.bat > debug.log 2>&1
    

Then inspect:

notepad debug.log
    

12. Turn On Command Extensions Output

setlocal EnableExtensions
    

13. Diagnose Infinite Loops

echo Loop start: %time%
REM your loop here
echo Loop end: %time%
    

14. Check Tokens & Delims for for /f

echo Line: %%a
for /f "tokens=1,2 delims=," %%a in (file.txt) do (
  echo First: %%a Second: %%b
)
    

15. Summary