← Home

Batch Lab

FOC
Basics

@echo off hides command echo. echo prints text. pause waits for a keypress. rem starts a comment.

@echo off
echo Hello, World!
rem This is a comment
pause
Variables & Input
rem Set a variable
set myvar=Hello

rem Use a variable
echo %myvar%

rem User input
set /p name=Enter your name:
echo Hello, %name%!

rem Arithmetic
set /a sum=5 + 3
set /a product=%x% * %y%
echo %sum%  %product%

rem Delayed expansion (inside blocks)
setlocal enabledelayedexpansion
set val=test
echo !val!
Conditionals
rem String comparison
if "%var%"=="value" (
    echo Match!
) else (
    echo No match.
)

rem Numeric comparison
if %num% GEQ 10 echo Big number

rem File existence
if exist "file.txt" (
    echo Found it!
) else (
    echo Not found.
)

rem Comparison operators:
rem EQU (==)  NEQ (!=)  LSS (<)
rem LEQ (<=)  GTR (>)   GEQ (>=)
rem /i = case-insensitive
Loops
rem Count from 1 to 10
for /l %%i in (1,1,10) do echo %%i

rem Loop through files
for %%f in (*.txt) do echo %%f

rem Loop through file lines
for /f "tokens=*" %%a in (data.txt) do echo %%a

rem Loop with delimiters
for /f "tokens=1,2 delims=," %%a in (data.csv) do (
    echo Name: %%a  Age: %%b
)

rem Note: In scripts use %%i
rem At command prompt use %i
File Operations
rem Create / write
echo Hello > file.txt          & rem overwrite
echo World >> file.txt         & rem append

rem Copy / Move / Delete
copy source.txt dest.txt
move old.txt new.txt
del file.txt
ren file.txt newname.txt

rem Directories
mkdir newfolder
rmdir /s /q oldfolder
dir /b                         & rem bare listing

rem Rename pattern
for %%f in (*.txt) do ren "%%f" "%%~nf_backup.txt"
Labels & Goto
rem Labels define jump points
:start
echo Menu: 1=Greet 2=Date 3=Exit
set /p choice=Choose:

if "%choice%"=="1" goto greet
if "%choice%"=="2" goto showdate
if "%choice%"=="3" goto end

:greet
echo Hello!
goto start

:showdate
date /t
goto start

:end
echo Goodbye!
String Manipulation
setlocal enabledelayedexpansion
set str=Hello World

rem Substring: !str:~start,length!
echo !str:~0,5!               & rem Hello
echo !str:~6!                  & rem World

rem String replace
set newstr=!str:World=Batch!
echo !newstr!                  & rem Hello Batch

rem String length (loop method)
set len=0
:loop
if "!str:~%len%,1!"=="" goto done
set /a len+=1
goto loop
:done
echo Length: %len%
Useful Tricks
rem Script directory path
echo %~dp0

rem Open a file
start notepad file.txt

rem Delay execution
timeout /t 5

rem Errorlevel check
dir nofile.txt 2>nul
if %errorlevel% neq 0 echo File not found

rem Suppress errors
command 2>nul

rem Get date/time
date /t
time /t
SCORE: 0   STREAK: 0   1/15
SCORE: 0   STREAK: 0   1/15