Introduction
A batch file is a text file of commands for the DOS or Windows command interpreter, run
one line after another as if they had been typed. The .bat extension goes
back to MS-DOS, where COMMAND.COM ran them and AUTOEXEC.BAT
ran at every start.
Windows NT brought a new interpreter, cmd.exe, and the .cmd
extension, which OS/2 also used. cmd.exe runs both today. The difference is
small: a few built-in commands, such as set and path, reset
ERRORLEVEL on success in a .cmd file and leave it alone in a
.bat file.
Structure
A batch file is plain text, normally with Windows line ends, and cmd.exe
reads it in the console’s code page, not as Unicode. Many files start with
@echo off, which stops each command being printed before it runs. Comments
use rem, or ::, which is really a label nothing jumps to.
%NAME%expands a variable, set withset NAME=value. Withsetlocal enabledelayedexpansion,!NAME!expands it when the line runs and not when it is read, which matters inside loops.%1to%9are the arguments,%*is all of them, and%~dp0is the folder holding the script.- A line starting with a colon is a label.
gotojumps to one andcall :labelruns it as a subroutine. - A
forloop variable is written%%Fin a batch file and%Fat the prompt. ^escapes the next character, and at the end of a line it continues the command on the next.
@echo off
rem Copy each file named on the command line into a backup folder.
if "%~1"=="" goto usage
for %%F in (%*) do (
copy "%%~F" "%USERPROFILE%\Backup" >nul
if errorlevel 1 echo Could not copy %%~F
)
exit /b 0
:usage
echo Usage: %~nx0 file [file ...]
exit /b 1
Links
Software
Reference
- Windows commands – Microsoft’s reference to the commands
- cmd – Microsoft’s page on the interpreter and its options
- SS64 CMD reference – independent guide to commands and batch syntax