DOS Batch Files

2008 Oct 18


Batch files must have the extension: *.BAT.


Batch File Commands
CALL Executes a batch file from within another batch file
CHOICE Accepts a single keystroke from the keyboard
COMMAND Runs anothr copy of the command interpreter
ECHO Echoes text to the screen
FOR FOR-IN-DO loop
GOTO Jumps to a labeled line, :LABEL
IF Conditional DOS command execution
PAUSE Waits for keystroke before continuing
REM Denotes a remark (comment) line
SHIFT Shifts batch file parameters down one place

Batch File Options
Option DOS
VER
Syntax
label 1.0
...
:label optional_comment

label : up to 8 characters
  • Colon must be first character on line
  • Only first 8 characters of label are significant, rest are ignored
  • If a label appears multiple times, first occurence is used by GOTO
  • Labels can use characters: a..z A..Z _ 0..9 & @ ^ _ { } $ ! # ( ) ' ` ~
optional_comment : ignored
replaceable
parameters
1.0
...
%n

n : 0..9
  • %0 : name of batch file as entered on the command line
  • %1 : first parameter on command line
  • %2 : second parameter on command line, etc.
  • Spaces, tabs, commas, semicolons : are valid argument delimiters
    (unless enclosed in "double quote marks")
  • Applies even within double quote marks
  • To use a % as is write %%, which is replaced with a single % (this is why
    variables in a FOR on the command line are %v, but %%v in a batch file)
  • If more than 9 parameters are needed use the SHIFT command; e.g.
    REM Display a series of files one screen at a time
    :START
    IF "%1"=="" GOTO END
    IF NOT EXIST %1 GOTO END
    TYPE %s | MORE
    SHIFT
    GOTO START
    :END
    
optional_comment - ignored
Input /
Output
Redirection
2.0
...
> Sends stdout to a named file, overwriting if it exists
>> Appends stdout to a named file, creating if it does not exist
<Redirects stdin from keyboard to read a file
| Pipes stdout from command on left to stdin of command on right
Environment
Variables
4.0
...
%envir%

envir : Environment variable name (along %...%) replaced
  • Case does not matter
  • Works within "double quote marks"
  • To use a % as is write %%, which is replaced with a single % (this is why
    variables in a FOR on the command line are %v, but %%v in a batch file)
  • If %envir% is not found then an empty string is used
Echo
Disable
4.0
...
@command_line

  • The @ must be first character on line
  • Suppresses echoing command_line to the screen

2005-2008