A Batch file is the Windows equivalent to a shell script. It is supported by Windows, MS-DOS, and OS/2. Since DOS has no file extension mapping, the extension is hardwired to '.BAT' it can also be '.bat' but never a mixed case. However in Windows, They can also end in '.cmd'
Contents Of A Batch File
A Batch file is a plain text file that is interpreted by a command processor, usually cmd.exe on Windows and COMMAND.COM on DOS.
Labels And GOTO
It features some flow control features through label's (prefixed by a ':') and GOTO's.
Echo allows you to print to the screen, and has a special function, "@echo off" to turn off the commands from the batch itself.
Pause allows you to make the user input a confirmation key press before continuing.
Comments in a Batch are single line, starting with '::' or 'rem'
Set allows you to set variables in the shell. These variables can be used inside the batch and are local to the shell, meaning all future batch files can access them. But because they are global to the shell, if in Windows the shell is auto-closed, the variables are erased, one system set variable is PATH. To use a Variable, you must pre-fix and post-fix it with a '%'.
IF is the only logic command of a Batch ELSE only exists as an extension of it, syntax is "IF [NOT] %VARIABLE [== %VAR2] COMMAND [ELSE OTHER.EXE]"
WARNING! This method only works in windows 2000 and up. If you need input in a batch file, you can use "SET /P VARIABLE=Message" where VARIABLE is a variable to set and Message is text to put before the prompt. If the user does not input any information, the variable is set to the previous value, if it is a new variable, it will remain undefined.
Reading Command Line Arguments
As there is no proper input method in a batch, command line arguments can be a valuable tool. To access them, you would use the numerical variables. For example, the first argument is %1, the second is %2, and so on.
To preform any mathematical equations, you use "SET /a VARIABLE=n?p" where VARIABLE is the variable to set, n and p are values or variables, and '?' is the operator, the operators are as follows:
- Add +
- Subtract -
- Multiply *
- Divide /
- Modulus %
- AND &
- OR |
- XOR ^
- Left Bit-wise shift <<
An Example Batch File can be seen below, it takes three command line arguments, the file is a simple calculator.
:: calc.bat -- Command line calculator, takes three arguments IF %2==+ GOTO ADD IF %2==- GOTO SUB IF %2==* GOTO MUL IF %2==/ GOTO DIV ECHO No Valid Operator Found EXIT :ADD SET /a VAL=%1%+%2% GOTO DISP :SUB SET /a VAL=%1%-%2% GOTO DISP :MUL SET /a VAL=%1%*%2% GOTO DISP :DIV SET /a VAL=%1%/%2% GOTO DISP :DISP ECHO %VAL% EXIT
- Batch Files on Wikipedia