Department of Software Engineering
Mehran University of Engineering and Technology, Jamshoro
Course: SWE 225 – Operating System
Instructor Asadullah Channar Practical/Lab No. 03
Date CLOs 3
Signature Assessment Score
Topic Working with Batch Files
Objectives To enable students to automate their tasks with batch files
Lab Discussion: Theoretical concepts and Procedural steps
Batch Script is incorporated to automate command sequences which are
repetitive in nature. Scripting is a way by which one can alleviate this necessity
by automating these command sequences in order to make one’s life at the shell
easier and more productive. In most organizations, Batch Script is incorporated
in some way or the other to automate stuff.
Some of the features of Batch Script are −
• Can read inputs from users so that it can be processed further.
• Has control structures such as for, if, while, switch for better automating
and scripting.
• Supports advanced features such as Functions and Arrays.
• Supports regular expressions.
• Can include other programming codes such as Perl.
Some of the common uses of Batch Script are −
• Setting up servers for different purposes.
• Automating housekeeping activities such as deleting unwanted files or log
files.
• Automating the deployment of applications from one environment to
another.
• Installing programs on various machines at once.
Batch scripts are stored in simple text files containing lines with commands that get
executed in sequence, one after the other. These files have the special extension bat
or cmd. Files of this type are recognized and executed through an interface
(sometimes called a shell) provided by a system file called the command interpreter.
On Windows systems, this interpreter is known as cmd.exe.
Comments
The official way to add a comment to a batch file is with the REM (Remark) keyword:
REM This is a comment!
Or use ::
:: This is a comment too!
Silencing Display of Commands in Batch Files
The first non-comment line of a batch file is usually a command to turn off printing
(ECHO’ing) of each batch file line.
@ECHO OFF
The @ is a special operator to suppress printing of the command line. Once we set
ECHO’ing to off, we won’t need the @ operator again in our script commands. You
restore printing of commands in your script with:
ECHO ON
Upon exit of your script, the command prompt will automatically restore ECHO to it’s
previous state.
Variables
There are two types of variables in batch files. One is for parameters which can be
passed when the batch file is called and the other is done via the set command.
Command Line Arguments
Batch scripts support the concept of command line arguments wherein
arguments can be passed to the batch file when invoked. The arguments can be
called from the batch files through the variables %1, %2, %3, and so on.
The following example shows a batch file which accepts 3 command line
arguments and echo’s them to the command line screen.
@echo off
echo %1
echo %2
echo %3
SET Command
The other way in which variables can be initialized is via the ‘set’ command.
Following is the syntax of the set command.
Syntax: set /A variable-name=value
set /p variable-name=prompt_user
where,
• variable-name is the name of the variable you want to set.
• value is the value which needs to be set against the variable.
• /A – This switch is used if the value needs to be numeric in nature.
• /p – This switch is used if we want user to give input at run time. The
following example shows a simple way the set command can be used.
Example:
@echo off
set /p message=Write message to display:
echo %message%
• In the above code snippet, a variable called message is defined which will
be set with the value that user will give at run time.
• To display the value of the variable, note that the variable needs to be
enclosed in the % sign.
Stdin, Stdout, Stderr
DOS, like Unix/Linux, uses the three universal “files” for keyboard input, printing
text on the screen, and the printing errors on the screen. The “Standard In” file,
known as stdin, contains the input to the program/script. The “Standard Out”
file, known as stdout, is used to write output for display on the screen. Finally,
the “Standard Err” file, known as stderr, contains any error messages for display
on the screen. Each of these three standard files, otherwise known as the
standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0,
stdout is file 1, and stderr is file 2.
Redirection
A very common task in batch files is sending the output of a program to a log file.
The > operator sends, or redirects, stdout or stderr to another file. For example,
you can write a listing of the current directory to a text file:
DIR > temp.txt
The > operator will overwrite the contents of temp.txt with stdout from the DIR
command. The >> operator is a slight variant that appends the output to a target
file, rather than overwriting the target file.
A common technique is to use > to create/overwrite a log file, then use >>
subsequently to append to the log file.
SomeCommand.exe > temp.txt
OtherCommand.exe >> temp.txt
By default, the > and >> operators redirect stdout. You can redirect stderr by
using the file number 2 in front of the operator:
DIR SomeFile.txt 2>> error.txt
To use the contents of a file as the input to a program, instead of typing the input
from the keyboard, use the < operator.
SORT < SomeFile.txt
You can quickly create a new text file, say maybe a batch script, from just the
command line by redirecting the command prompt’s own stdin, called CON, to a
text file. When you are done typing, hit CTRL+Z, which sends the end-of-file
(EOF) character.
TYPE CON > output.txt
Decision Making
Decision-making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false. Batch Scripts support if/then conditions;
Syntax: if condition (rem do something
)else if (rem do something else
)else (rem do the default thing)
Checking that a File or Folder Exists
IF EXIST "temp.txt" ECHO found
Or the converse:
IF NOT EXIST "temp.txt" ECHO not found
Both the true condition and the false condition:
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
NOTE: It’s a good idea to always quote both operands (sides) of any IF check.
This avoids nasty bugs when a variable doesn’t exist, which causes the operand
to effectively disappear and cause a syntax error.
Checking If a Variable Matches a Text String
SET var=Hello, World!
IF "%var%"=="Hello, World!" (
ECHO found
)
Or with a case insensitive comparison
IF /I "%var%"=="hello, world!" (
ECHO found
)
Arithmetic Comparisons
SET /A var=1
IF /I "%var%" EQU "1" ECHO equality with 1
IF /I "%var%" NEQ "0" ECHO inequality with 0
IF /I "%var%" GEQ "1" ECHO greater than or equal to 1
IF /I "%var%" LEQ "1" ECHO less than or equal to 1
IF /I "%var%" LSS "1" ECHO less than 1
IF /I "%var%" gtr "1" ECHO greater than 1
For Loop
Batch scripting supports for loops
Syntax: FOR %%i in %list% DO (anything)
Looping through files
Rem shows all docx files in the directory
FOR %%I IN (path\*.docx) DO @ECHO %I
Rem Recursively loop through files in all subfolders of the path
FOR -R %%I IN (path\*) DO @ECHO %I
Looping through directories
Rem shows all folders in the path
FOR /D %%I IN (path\*) DO @ECHO %I
Rem Recursively loop through all subfolders of the path
FOR -R /D %%I IN (path\*) DO @ECHO %I
Useful syntax in loops
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
Lab Tasks
1. Create a batch script that opens your 5 favorite websites at once.
2. Create a batch script that organizes your files in a directory based on their
extensions.
For Example: Puts all .txt files in .txt folder, all .png files in .png folder
Note: The directory to organize should be given by user at runtime (+1 Mark)
3. Create a batch script that work as a simple calculator.