Reference > Batch File Reference

SwansonSoftware Home | Site Index | View With Frames

Final Version 1.01 August 17 2003

Contents

  1. Introduction
  2. Commands
  3. Parameters
  4. Filters
  5. Redirection Operators
  6. Programming
  7. Command Cross Reference
  8. References

Introduction

Next | Top of page

This reference was written from the point-of-view that no one is writing batch programs for MS-DOS, and that few people are writing batch programs for Windows 95. Most of the reference material is based on Windows 2000 and XP, with notes about functionality that differs between Windows 98 and 2000.

Batch file technology has evolved with each version of MS-DOS and early versions of Windows, and is now supplanted at least partly by the Windows Scripting Host (WSH). WSH gives you much greater flexibility and power because it lets you create scripts with powerful scripting languages like VBScript and JavaScript.

Ansi.sys - a toy-box for batch-file developers - gave batch programs the capability to change foreground and background colors, position the cursor, apply different text attributes, redefine keyboard keys and assign commands to function keys. Beginning with Windows 98 Millenium, terminate-and-stay-resident (TSR) real-mode drivers like ansi.sys were excluded from Windows startup in the attempt to reduce start-up time and improve stability ("device=" entries in config.sys are not processed unless you start in real mode).

Some of the capabilities provided by ansi.sys are available as environment variables, accessible through the command shell using SET and CMD; other MS-DOS commands are no longer available and some are replaced by new functionality built directly into Windows.


Commands

Next | Previous | Top of page

Batch file commands include the following:


In addition to the standard batch file commands there are some DOS commands that are particularly useful for batch programs:


CALL

Next | Previous | Commands | Top of page

Allows a batch file to run another batch file and then continue execution of the calling batch file.

Syntax:

CALL [[Drive:][Path] FileName [BatchParameters]] [:label [arguments]]

Where

Notes:

Example


This batch file runs a second batch file using the CALL command:
    VER
    CALL bat2
    
bat2.bat contains the following commands:
    SET PATH=%PATH%;C:\Temp
    ECHO Path is now %PATH%
    

Output:


    Microsoft Windows 2000 [Version 5.00.2195]
    Path is now C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;C:\Temp
    
Commands > CALL

ECHO

Next | Previous | Commands | Top of page

Suppresses or enables the display of command names as MS-DOS executes the commands within a batch file.

Syntax:

echo [{on|off}] [message]

Where

Notes:

Example 1


The following batch file contains the DATE and TIME commands. When you run the batch file, DOS displays each command name as the command executes.
    TIME
    DATE
    

Output:


    C:\> TIME
    Current time is 22:11:50.50
    Enter new time:

    C:\> DATE
    The current date is: Sat 06/30/2001
    Enter new date: (mm-dd-yy)
    

Example 2


The following batch file suppresses command-name display with the @ECHO OFF command:

    @ECHO OFF
    TIME
    DATE
    

Output:

    Current time is 22:11:50.50
    Enter new time:
    The current date is: Sat 06/30/2001
    Enter new date: (mm-dd-yy)
    
Commands > ECHO

ENDLOCAL

Next | Previous | Commands | Top of page

Ends localization of environment changes by restoring environment variables to their values before the matching SETLOCAL command.

Syntax:

endlocal

Notes:


Commands > ENDLOCAL

FOR

Next | Previous | Commands | Top of page

Repeats processing on a set of files.

Syntax:

for {%variable|%%variable} in (set) do command [ CommandLineOptions]

Where


Commands > FOR

IF

Next | Previous | Commands | Top of page

IF is used to test for specific conditions. It has limited capabilities in batch files, compared to other languages: there are three conditions that can be tested. Including the NOT operator allows you to test the opposite condition.

First Form

Syntax:

IF ERRORLEVEL DOSCommand

Second Form

Syntax:

IF EXIST DOSCommand

Third Form

Syntax:

IF StringOne==StringTwo DOSCommand


Commands > IF

GOTO

Next | Previous | Commands | Top of page

Directs processing to a line identified by a label. Processing begins on the line following the label.

Syntax:

goto label

Where

Notes:


Commands > GOTO

NOT operator

Next | Previous | Commands | Top of page

Reverses the result of a true or false result in an IF command.

Syntax:

IF NOT condition dos-command

Commands > NOT operator

PAUSE

Next | Previous | Commands | Top of page

Temporarily suspends execution and displays an optional message. Execution continues when the user presses any key.

Syntax:

PAUSE [message]

Notes:


Commands > PAUSE

REM

Next | Previous | Commands | Top of page

Allows you to put remarks in a batch file.

Syntax:

rem [text]

Notes:

Example


You might include several lines at the top of your batch file that explain who wrote it, when it was written, etc.
    REM ftp database extract from host.
    REM Author: G. Swanson
    REM 2/10/1999
    
Commands > REM

SETLOCAL

Next | Previous | Commands | Top of page

Changes (localizes) environment variables for the batch file. Localization ends when a matching ENDLOCAL command is encountered or when the end of the batch file is reached.

Syntax:

setlocal {enableextension | disableextensions} {enabledelayedexpansion | disabledelayedexpansion}

Where

Notes:


Commands > SETLOCAL

SHIFT

Next | Previous | Commands | Top of page

Changes the position of parameters in a batch file

Syntax:

shift [/n]

Where

Notes:


Commands > SHIFT

CHOICE

Next | Previous | Commands | Top of page

Displays message and waits for user input. Input is defined as a set of keys in the setup for CHOICE; the exit-status returned by CHOICE is used to determine which key the user pressed.

Syntax:

CHOICE [/C[:]Keys][/N][/S][/T[:]Default,Seconds][Prompt]

Where

Notes:


Commands > CHOICE

CMD

Next | Previous | Commands | Top of page

16-bit version is COMMAND

Loads a second command processor into memory. The command shell program provides direct communication between the user and operating system. MS-DOS and Windows versions through Windows 98 (pre-millenium edition) used COMMAND.COM to execute batch programs, while later Windows versions use CMD.EXE. Windows Script Host runs more sophisticated scripts in the command shell.

Syntax:

cmd [[{/c|/k}] [/s] [/q] [/d] [{/a|/u}] [/t:fg] [/e:{on|off}] [/f:{on|off}] [/v:{on|off}] string]

Where

Notes:


Commands > CMD

EXIT

Next | Previous | Commands | Top of page

Use when calling another batch file from within a batch file. You must call EXIT to return processing to the calling batch file.

Syntax:

exit [/b] [ExitCode]

Where

Notes:


Commands > EXIT

NUL

Next | Previous | Commands | Top of page

The NUL device - referred to as a bit bucket - is useful for disposing of unwanted output.

Syntax:

nul

Example


    ECHO the following PAUSE command will display a prompt:
    PAUSE
    ECHO the following PAUSE command will not display a prompt:
    PAUSE > NUL
    
Commands > NUL

Parameters

Next | Previous | Top of page

Parameters are the command-line arguments to your batch program. Cmd.exe provides variables %0 through %9, with %0 reserved for the batch-file name. If you have more than 9 input parameters to your batch program, you can use SHIFT to access them.

Modifiers

Modifiers expand batch parameters by taking drive and directory information and creating a partial or complete file or directory name. The syntax is
%~modifier.

Modifiers you can use include the following:

Modifier Description
%~1 Expands %1 and removes surrounding quotation marks.
%~f1 Expands %1 to a fully qualified path name.
%~d1 Expands %1 to a drive letter.
%~p1 Expands %1 to a path.
%~n1 Expands %1 to a file name.
%~x1 Expands %1 to a file extension.
%~s1 Expanded path contains short names only.
%~a1 Expands %1 to file attributes.
%~t1 Expands %1 to date and time of file.
%~z1 Expands %1 to size of file.
%~$PATH:1 Searches the directories listed in the PATH environment variable and expands %1 to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found, this modifier expands to the empty string.

You can get compound results using combinations of modifiers listed in the following table:

Modifier Description
%~dp1 Expands %1 to a drive letter and path.
%~nx1 Expands %1 to a file name and extension.
%~dp$PATH:1 Searches the directories listed in the PATH environment variable for %1 and expands to the drive letter and path of the first one found.
%~ftza1 Expands %1 to a dir-like output line.

Filters

Next | Previous | Top of page

Filter commands give you control over the display of information your batch program processes. Redirection operators are used with filter commands to determine their behavior.

Filter commands include the following:



MORE

Next | Previous | Filters | Top of page

Displays command output or file contents in one command prompt window at a time.

Syntax:

more [[/c] [/p] [/s] [/tn] [+n]] < [Drive:] [Path] FileName
Or
command | more [/c] [/p] [/s] [/tn] [+n]
Or
more [/c] [/p] [/s] [/tn] [+n] [files]

Where

Notes:

Example


    tree c:\inetpub | more
    
Filters > MORE

FIND

Next | Previous | Filters | Top of page

Searches files and command output for specified characters. Displays any lines that contain the specified characters.

Syntax:

find [/v] [/c] [/n] [/i] "string" [[Drive:][Path]FileName[...]]

Where

Notes:


Filters > FIND

SORT

Next | Previous | Filters | Top of page

Reads input from the keyboard, pipe, or file; sorts the data, and writes the result to screen, file, or another device.

Syntax:

sort [/r] [/+n] [/m kilobytes] [/l locale] [/rec characters] [[drive1:][path1]filename1] [/t [drive2:][path2]] [/o [drive3:][path3]filename3]
Or
[command |] sort [/r] [/+n] [/m kilobytes] [/l locale] [/rec characters] [[drive1:][path1]filename1][/t [drive2:][path2]] [/o [drive3:][path3]filename3]

Where

Notes:

Example


To sort a file:

    sort filename.txt
To sort output from a command - this example finds each line with the name "Swanson" in the contacts.txt file and sorts the output:
    find "Swanson" contacts.txt | sort
    
Filters > SORT

Redirection Operators

Next | Previous | Top of page

Redirection operators redirect command input and output stream locations. Stream location is referred to as a handle. Handles have numeric values, three of which are pre-defined: STDIN, STDOUT, and STDERR.

Default command input is sent via STDIN from the keyboard to the command processor (command.com or cmd.exe). Default command output is sent via STDOUT from the command processor to the Command Prompt window.

Redirection operator Description
> Writes command output to a file or a device, such as a printer, instead of the command prompt window.
< Reads command input from a file, instead of reading input from the keyboard.
>> Appends command output to the end of a file.
>& Writes the output from one handle to the input of another handle.
<& Reads the input from one handle and writes it to the output of another handle.
| Reads the output of one command and writes it to the input of another command.

Handle Value Description
STDIN 0 Keyboard input.
STDOUT 1 Output to the Command Prompt window.
STDERR 2 Error output to the Command Prompt window.
UNDEFINED 3-9 Application-defined and specific to each tool.


If you do not specify a handle when using redirection operators with the command processor, the default handle used by the < operator is zero (0) and the default handle used by the > operator is one (1). The syntax for redirection to existing handles is as follows:

&handle

For example you can redirect STDERR into STDOUT with this command:

    1<&2
    


Programming

Next | Previous | Top of page


Interrupting Batch File Execution

Next | Previous | Programming | Top of page

You can interrupt execution of the commands in a batch file by holding down the Ctrl key and press C. DOS displays ^C and the message:

    Terminate batch job (Y/N)?
    

If you press Y, DOS immediately stops processing the batch file. If you press N, DOS ends the command it is currently executing, and continues execution with the next command.

Programming

Redirecting Output

Next | Previous | Programming | Top of page

You must specify I/O redirection on the specific command line(s) of the batch file if you want to send output of the batch file somewhere other than the screen.

Syntax:

>  creates a new file;
>>  appends to the file.

Programming

Running One Command at a Time

Next | Previous | Programming | Top of page

When you have a batch file that is not working correctly, you can step through the file to find out which command is causing the problem. Use the COMMAND batch file command with the /Y and /C switches followed by the file name. DOS runs the file and stops at each command, with a prompt that lets you run the command or skip it.

Syntax:

COMMAND /Y /C  filename

Programming

Suspend Processing

Next | Previous | Programming | Top of page

When your batch file needs to wait until you perform some task, you can use the PAUSE command to display a message, suspending execution until you press a key to continue.

When the PAUSE command executes, it displays the message specified in its command line (if ECHO is not OFF), followed by the message:

    Press any key to continue...
    
Programming

Command Cross Reference

Next | Previous | Top of page

View the list of commands at the command prompt on Windows 2000 by typing help and pressing Enter. The HELP command is not available on Windows 98.

To view help for a command, open a command prompt (Windows 2000, XP) or DOS window (Windows 98) and enter /? command and press ENTER.

Command 98 2K Description
ASSOC N Y Displays or modifies file extension associations
AT N Y Schedules commands and programs to run on a computer.
ATTRIB Y Y Displays or changes file attributes.
BREAK Y Y Sets or clears extended CTRL+C checking.
CACLS N Y Displays or modifies access control lists (ACLs) of files.
CALL Y Y Calls one batch program from another.
CD Y Y Displays the name of or changes the current directory.
CHCP Y Y Displays or sets the active code page number.
CHDIR Y Y Displays the name of or changes the current directory.
CHKDSK Y Y Checks a disk and displays a status report.
CHKNTFS N Y Displays or modifies the checking of disk at boot time.
CHOICE Y N Displays message and waits for user input.
CLS Y Y Clears the screen.
CMD N Y Starts a new instance of the Windows 2000 command interpreter.
COLOR N Y Sets the default console foreground and background colors.
COMMAND Y N Starts a new instance of the command interpreter.
COMP N Y Compares the contents of two files or sets of files.
COMPACT N Y Displays or alters the compression of files on NTFS partitions.
CONVERT N Y Converts FAT volumes to NTFS. You cannot convert the current drive.
COPY Y Y Copies one or more files to another location.
CTTY Y N Changes the terminal device used to control your system.
DATE Y Y Displays or sets the date.
DEL Y Y Deletes one or more files.
DELTREE Y N Deletes a directory and all the subdirectories and files in it.
DIR Y Y Displays a list of files and subdirectories in a directory.
DISKCOMP N Y Compares the contents of two floppy disks.
DISKCOPY Y Y Copies the contents of one floppy disk to another.
DOSKEY Y Y Edits command lines, recalls Windows 2000 commands, and creates macros.
DRVSPACE Y N Displays list of drives and properties of each drive.
ECHO Y Y Displays messages, or turns command echoing on or off.
EMM386 Y N Turns on or off EMM386 expanded memory support.
ENDLOCAL N Y Ends localization of environment changes in a batch file.
ERASE Y Y Deletes one or more files.
EXIT Y Y Quits the CMD.EXE (Windows 2000) or Command.com (Windows 98) program (command interpreter).
FC Y Y Compares two files or sets of files, and displays the differences between them.
FDISK Y N Configures a hard disk for use with MS-DOS.
FIND Y Y Searches for a text string in a file or files.
FINDSTR N Y Searches for strings in files.
FOR Y Y Runs a specified command for each file in a set of files.
FORMAT Y Y Formats a disk for use with Windows 2000.
FTYPE N Y Displays or modifies file types used in file extension associations.
GOTO Y Y Directs the Windows 2000 command interpreter to a labeled line in a batch program.
GRAFTABL N Y Enables Windows 2000 to display an extended character set in graphics mode.
HELP N Y Provides Help information for Windows 2000 commands.
IF Y Y Performs conditional processing in batch programs.
LABEL Y Y Creates, changes, or deletes the volume label of a disk.
LOADHIGH Y N Loads a program into the upper memory area.
MD Y Y Creates a directory.
MEM Y N Displays the amount of used and free memory in your system.
MKDIR Y Y Creates a directory.
MODE Y Y Configures a system device.
MORE Y Y Displays output one screen at a time.
MOVE Y Y Moves one or more files from one directory to another directory.
MSCDEX Y N Configures the MS-DOS subsystem to use CD-ROM drives.
NLSFUNC Y N Loads country-specific information.
PATH Y Y Displays or sets a search path for executable files.
PAUSE Y Y Suspends processing of a batch file and displays a message.
POPD N Y Restores the previous value of the current directory saved by PUSHD.
PRINT N Y Prints a text file.
PROMPT Y Y Changes the Windows 2000 command prompt.
PUSHD N Y Saves the current directory then changes it.
RD Y Y Removes a directory.
RECOVER N Y Recovers readable information from a bad or defective disk.
REM Y Y Records comments (remarks) in batch files or CONFIG.SYS.
REN Y Y Renames a file or files.
RENAME Y Y Renames a file or files.
REPLACE N Y Replaces files.
RMDIR Y Y Removes a directory.
SCANDISK Y N Checks drive for errors.
SET Y Y Displays, sets, or removes Windows 2000 environment variables.
SETLOCAL N Y Begins localization of environment changes in a batch file.
SETVER Y N Sets the MS-DOS version number that Windows reports to a program.
SHIFT Y Y Shifts the position of replaceable parameters in batch files.
SMARTDRV Y N Installs and configures the SMARTDrive disk-caching utility.
SORT Y Y Sorts input.
START Y Y Starts a separate window to run a specified program or command.
SUBST Y Y Associates a path with a drive letter.
SYS Y N Copies MS-DOS system files and command interpreter to a disk you specify.
TIME Y Y Displays or sets the system time.
TITLE N Y Sets the window title for a CMD.EXE session.
TREE N Y Graphically displays the directory structure of a drive or path.
TYPE Y Y Displays the contents of a text file.
VER Y Y Displays the Windows 2000 version.
VERIFY Y Y Tells Windows 2000 whether to verify that your files are written correctly to a disk.
VOL Y Y Displays a disk volume label and serial number.
XCOPY Y Y Copies files and directory trees.

Command Cross Reference

References


Jamsa, Kris, 1994, Concise Guide to MS-DOS Batch Files: Microsoft Press, 218 pages. ISBN 1-55615-638-3

Microsoft TechNet online reference - search for "command-line reference."


Top of page | Previous