Windows 7 / Getting Started

# Multiple Commands on One Line

CMD lets you type multiple separate commands on one command line, separated by an ampersand (&), as in this example:

dir & ping ftp.microsoft.com & ftp ftp.microsoft.com

CMD runs the three commands in turn, as if they had been entered on separate command lines:

dir
ping ftp.microsoft.com
ftp ftp.microsoft.com


This sounds trivial, but it can be handy. First, when you're typing the same several commands over and over, you can simply press the up-arrow key and use the history feature to recall all the commands at once.

Also, in batch files, this feature can be used to put several commands on one if statement, as in this example:

if not exist list.dat dir c:\in >list.dat & dir c:\out >>list.dat

If the file list.dat does not exist, then CMD runs the two dir commands in turn. This can simplify the batch program.

There are two other ways to specify multiple commands on the same line. If you separate commands with two ampersands instead of one, for example,

ping ftp.microsoft.com && ftp ftp.microsoft.com

the second and subsequent commands are only run if the preceding command is successful (that is, if it exited with an error status value of 0).This lets you create lists of commands that don't plow on after encountering an error.

Another variation lets you use || to indicate that the second command is to be run only if the first command fails-that is, if the first command exits with a nonzero error status, as in this example:

firstcommand || echo The first command failed