How to write a basic batch script
Overview
A batch file is a plain-text file ending in .bat or .cmd. CMD executes its lines in order, making repeatable tasks easy.
Begin with read-only or copy-based automation. Add deletion only after validating paths, handling errors, and testing with disposable data.
- Save the example as
hello.cmd, then runhello.cmd Student. %~dp0is the script's drive and folder, which is safer than assuming the current directory.- Inside batch files, FOR variables use two percent signs such as
%%F.
Commands to try
Type each command at the prompt, then press Enter. Replace sample names and paths with ones that exist on your computer.
Commands are generally not case-sensitive, but preserving the spelling shown here makes scripts easier to read.
@echo off
setlocal
rem Show the first argument and script folder
echo Argument: %~1
echo Script folder: %~dp0
if "%~1"=="" (
echo Usage: %~nx0 name
exit /b 2
)
for %%F in ("%~dp0*.txt") do echo %%~nxF
endlocal
Useful options and details
Options change how a command behaves. Add spaces exactly as shown, and use the command's built-in help when an option is unfamiliar.
A path containing spaces must be enclosed in double quotes, such as "C:\My Files".
@echo offhides command echo while retaining output.setlocalkeeps variable changes local to the script.%1is the first argument;%*represents all arguments;exit /b codereturns a status.
Tips and common mistakes
Check the current folder and read the command output before assuming an operation succeeded.
Practice with disposable files first. Commands that delete, overwrite, or stop a process may not offer an Undo button.
- Double-clicking closes the window at completion; run the script from an open CMD while debugging.
- Quote every path variable that may contain spaces, and validate that it is defined before a destructive operation.
- Use
call other.cmdwhen control must return to the first script.
Safe practice
Create a temporary practice folder under your user profile so the examples cannot affect Windows system files.
After each command, inspect the result with dir or another read-only command before continuing.
- Create a script that prints its argument and current date.
- Add a missing-argument check.
- Run it from a different directory and confirm
%~dp0remains correct.