Skip to content

Latest commit

 

History

History
executable file
·
199 lines (142 loc) · 5.14 KB

File metadata and controls

executable file
·
199 lines (142 loc) · 5.14 KB

🐞 Debugging Batch Scripts

  1. 🔍 Using ECHO for Debugging

    📌 Purpose:

    ECHO is your primary debugging tool in batch. You can print variables, track flow, and show command results in real time.

    🧪 Examples:

    @ECHO OFF
    SET USERNAME=omkar
    
    :: Debug message
    ECHO The username is: %USERNAME%
    
    :: Debug current directory
    ECHO Current directory: %CD%

    ✅ Best Practices:

    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 PAUSE to inspect ECHO DEBUG && PAUSE

    🧪 Example: Debugging Execution Flow

    @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%
    )

  2. 🧮. Checking Variable Expansion

    Batch expands variables when the line is read, which can cause issues inside loops or IF blocks.

    ❌ Problematic Code:

    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.

    ✅ Fix: Use Delayed Variable Expansion

    @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.


    🔎 Debug Tip: Echo Variables with Delayed Expansion

    SET VAR=Test
    ECHO Without delayed: %VAR%
    
    SETLOCAL ENABLEDELAYEDEXPANSION
    ECHO With delayed: !VAR!
    ENDLOCAL

  3. 🚨 Handling Script Errors

    Batch scripts don’t throw exceptions, but you can catch issues using:

    • %ERRORLEVEL%
    • IF ERRORLEVEL
    • || and && operators

    ✅ Basic Error Checking

    COPY file.txt D:\backup\
    IF ERRORLEVEL 1 (
        ECHO [ERROR] Copy failed!
    ) ELSE (
        ECHO [INFO] Copy successful.
    )

    ⛓️ Use || to Short-Circuit on Error

    XCOPY C:\Data D:\Backup /E /I || ECHO [ERROR] Backup failed!

    🧱 Exit Codes with Subroutines

    CALL :DoTask
    IF ERRORLEVEL 1 (
        ECHO [ERROR] Task failed!
        EXIT /B 1
    )
    GOTO :EOF
    
    :DoTask
    REM Simulate failure
    EXIT /B 1

💡 Tips for Better Debugging

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

🧰 Combined Debugging Template

@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

✅ Summary

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