Batch Scripting Best Practices

Introduction

Batch is simple but extremely powerful when used correctly. Clean structure, safe variable usage, good error handling, and modular code turn a messy .bat file into a professional automation tool.

1. Always Start With

@echo off
setlocal enabledelayedexpansion
    

2. Use Clear Variable Names

set /a fileCount=0
set srcFolder="C:\Input"
    

3. Don’t Hardcode Paths

set app=%APPDATA%\CodeTweakrs
mkdir "%app%"
    

4. Put Important Code Into Functions

call :BackupFolder "C:\Data"
exit /b

:BackupFolder
echo Backing up %~1
rem backup logic here
exit /b
    

5. Check for Errors

copy file.txt backup.txt
if errorlevel 1 (
  echo Copy failed!
)
    

6. Use Quotes Around Paths

copy "%USERPROFILE%\Desktop\file.txt" "D:\Backup\"
    

7. Document With Comments

rem This script cleans temp folders
    

8. Avoid Using goto Everywhere

Prefer *call functions* instead of spaghetti jumps.

9. Validate User Input

set /p choice=Enter option [1-3]:

if "%choice%"=="1" goto op1
if "%choice%"=="2" goto op2
if "%choice%"=="3" goto op3

echo Invalid choice.
    

10. Use for /f for Command Output

for /f %%a in ('hostname') do set host=%%a
echo Hostname is %host%
    

11. Avoid Global Pollution

Use setlocal / endlocal to contain variables.

12. Use Meaningful Exit Codes

exit /b 0  rem success
exit /b 1  rem error
    

13. Handle Missing Files

if not exist config.txt (
  echo config.txt missing!
  exit /b
)
    

14. Modular File Organization

Split big scripts into multiple .bat files and call them.

call cleanup.bat
call install.bat
call verify.bat
    

15. Logging

echo Starting update >> log.txt
echo Completed >> log.txt
    

16. Avoid Useless Echo Spam

Keep output clean and readable.

17. Always Use !var! in Loops

set count=0
for %%i in (*) do (
  set /a count+=1
  echo File !count!: %%i
)
    

18. Style and Spacing

19. Cleanup Temporary Files

del /q "%TEMP%\*.tmp"
    

20. Safety First

Summary