Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Prepared By
Vijay T. Patil
1
A Laboratory Manual for
Operating Systems
(22516)
Semester - V
2
Vidyalankar Polytechnic
CertifiCate
Mr/Ms…………………………………………………………………………
Roll No………………………. of Fifth Semester of Diploma in
Computer Engineering of Institute
Vidyalankar Polytechnic (Institute Code: 0568 / 1090) has
completed the Term Work satisfactory in Course Operating
Systems (22516) for the Academic Year
…………………….………………..
As prescribed in the Curriculum.
Name of Candidate:…………………………………………..…………………………………..
4
Sr. Title of Experiment Date of Date of Assessment Sign. Of
No. Performance Submission Mark out Teacher
of 10
7 Execute file and directory
manipulation commands
– diff, comm., pr, chmod,
mkdir, rmdir, cd, pwd, dir,
cmp. (Use wild card
character).
8 Execute text processing tr,
wc, cut, paste, spell, sort,
grep, more.
9 Use vi editor and perform
all editor commands.
10 Write and execute shell
script by using following
control statement
features – “if” statement.
11 Write and execute shell
script by using following
control statements
features – “for”
statement, exit, break,
continue.
12 Write shell script to find
out whether – Given file
exists?
13 Write shell script to find
out whether – File has
read, write and execute
permissions?
14 Write a program to
calculate total waiting and
turnaround time of n
processes with First Come
First Serve CPU scheduling
algorithm.
15 Write a ‘C’ program to
implement FIFO page
replacement algorithm.
5
Assessment Scheme
Performance Indicators (15 Marks) Weightage
Process related (15 marks) 30 %
1 Logic formation 10 %
2 Debugging Ability 10 %
3 Follow ethical practices 10 %
Product related (35 Marks) 70 %
4 Expected Output 30 %
5 Timely Submission 30 %
6 Answer to sample Questions 10 %
100 %
6
Program: Computer Engineering
Experiment No. 01
Title of Experiment Install and configure Linux (or alike) operating system.
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the concept of installation and booting
procedure
7
Practical Significance: Linux is the base of many of open source operating systems designed to replace
Windows and Mac OA. It is free to download and install on any computer. Because it is open source,
there are a variety of different versions or distributions, available developed by different groups. To
prevent hacking attempts, many organizations keep their Linux Operating System private. Many others
make their variations of Linux available publicly so the whole can benefit at large.
8
click on Continue….
Step:4 Select the Installation Type
If your system has new hard drive and if nothing installed on it, then you can choose the first option
“Erase disk & Install Ubuntu”.
If you want LVM based file system, then use third option “Use LVM with new Ubuntu Installation”
If you want to create customize partition table, the use last option “Some else”
click on Continue….
9
Step: 5 Select your respective Time Zone
Click on Continue…
10
Step:7 Set the Hostname of your system and User credentials that will be used after installation.
Click on Continue….
Step:7 As shown below Installation has started.
11
Once the installation is completed, it will ask to restart the Machine.
12
Ubuntu 15.04 Installation is Completed Now.
Similarly any open source installation shall be considered.
13
Advantages of Multiuser Operating system
Using multi-user operating system, we can perform multiple tasks at a time, i.e. we can run more
than one program at a time. Example: we can edit a word document while browsing the internet
Printing jobs in the office or library can be best handled by multi user operating system. Normal
OS cannot do the same job as printing can be mismatched.
Each user can access same document on own pc. For example, if one computer has a song or
movie then other computers attached with it will play that song or movie on their pc also.
Airlines also use this system and ticket reservation is also done by this system.
Teachers and library staff also use multi user operating system for handling books and for
searching books. The book record is stored in one computer and other terminals access to
single resource to query the books.
If one computer in the network gets error, then other computers not get affected and that
system handle this efficiently.
Exercise
1. Differentiate between command line OS and GUI based OS by giving example
Command Line Interface Graphical User Interface
It is a text-based interface used to interact with It is a visual-based interface which features the
software and operating system by typing use of graphic images, including Windows,
commands into the interface and receive a Icons, and Menus.
response in the same way.
CLI is faster and difficult to use than GUI. GUI is slower and easier to use than CLI.
CLI consumes low memory. It consumes high memory.
Not much flexible. GUI is more flexible.
Commands need to be remembered to be able Commands need not be remembered as they
to type and execute them. can be executed by simply clicking on icons.
CLI is less user friendly. GUI is more user friendly.
Examples: DOS, Unix etc. Example: Windows, Linux etc.
14
the CPU is switched to another job and so on. Eventually the first job finishes waiting and gets
the CPU back. As long as there is always some job to execute, the CPU will never be idle.
3. Which are the extra facilities provided by Unix other than windows OS
Unix OS Windows OS
No License fee, free of cost Required license fee, expensive
Open source Not open source
More secure Less secure
Unix is a Command Line User Interface Windows is Graphic User Interface Operating
system
Not even driven Windows is event driven
Not support plug and play Windows operating system support plug and
play
File system in Unix is (STD.ERR,STD.IO) File system in Windows is (FAT32,NTFS).
15
4. Enlist four features of following operating system
Window-98
Protection: Windows 98 includes additional protection for important files on your computer
such as backing up your registry automatically.
Improved support: Improved support for new devices and technologies such as ACPI, AGP, IEEE
1394, DVD, USB, and MMX.
FAT32: Windows 98 has the capability of converting your drive to FAT32 without losing any
information.
PnP: Improved PnP support, to detect devices even better than Windows 95.
Internet Explorer 4.0: Includes Internet Explorer 4.0
Customizable Taskbar: Windows adds new features to the Taskbarsuch as Quick Launch that
Windows 95 and Windows NT did not have.
Includes Plus!: Includes features only found in Microsoft Plus! free.
Active Desktop: Includes Active Desktop that allows for users to customize their desktop with
the look of the Internet.
New background properties: You can now set *.bmp, *.pcx, *.jpg, *.gif, and *.htm files as
your wallpaper (background).
Updated Microsoft Paint: The updated paint allows you to open *.bmp, *.pcx, *.jpg, and *.gif
files.
Multiple monitor support: Windows 98 now supports multiple monitors on one computer.
Personal Web Server: PWS supports CGI (common gateway interface) and ISAPI (Internet
Server Application Programming Interface) applications.
Improved floppy drive: Includes HSFLOP.PDR floppy disk driver that helps speed up access for
many floppy disk drives.
Other Software: Includes Dr. Watson, Outlook Express, FrontPage Express, Windows Media
Player, DirectX, NetMeeting, and more.
Windows-2000
Active Directory: Microsoft included Active Directory feature for the first time in Windows
2000 Server. Active Directory is used to store information about resources, users, or a group
and its attributes.
Distributed File System: Windows 2000 server operating system brought Distributed File
System (DFS) feature which enables users to distribute files across multiple servers over the
network.
NTFS 3.0 File system: Windows 2000 Server introduced new version of NTFS file system i.e.
NTFS 3.0 with new features such as file-system-level encryption, disk quotas, sparse files and
reparse points.
Virtual Private Network: This operating system provides virtual private network feature that
allows you to make your computer a remote server and enables other users to connect to the
server via VPN. With this feature, users can access shared files that reside on your system or
on the network.
Encrypted file systems protect sensitive data.
Multilingual version allows for User Interface and help to switch, based on login.
Includes broader support for high-speed networking devices, including native ATM and cable
modems.
Supports USB (Universal Serial Bus) and IEEE 1394 for greater bandwidth devices.
16
Windows-XP
Remote Desktop Windows XP professional OS enables user to use remote desktop connection
feature means they can sit at a PC and access another PC remotely.
Device Driver Rollback: This new Windows XP feature let users uninstall installed device driver.
If users install device driver that causes system instability, then they can easily roll back the
previous driver.
Built-in CD burner When Windows XP arrived, it came up with its own in-built CD burner
feature. Now there is no longer need to install CD burning software, user can burn files directly
via Windows Explorer.
Encrypted file system support multi-user: This feature is for Windows XP Professional,
encrypted file system make it possible to access encrypted files and folders by multiple users.
Device support improvement: Windows XP supports USB 2.0, Intel High Definition Audio based
hardware, FireWire, & Windows Image Acquisition based scanners etc.
17
Program: Computer Engineering
Experiment No. 02
Title of Experiment Execute general purpose commands date, time, cal,
clear, banner, tty, script, man
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands
18
Practical Significance: General purpose commands are inbuilt programs that can be invoked in
multiple ways. These commands work interactively from a terminal. A terminal that provides a
command line interface using a shell program.
Theoretical Background
Commands Description
date It displays system date and time
cal Displays calendar for current month
clear Clears the screen
banner Displays an argument string as a poster with maximum of ten characters per
line
tty Name of terminal
script Record login session
man It gives manual help for any command
3. Give single statement command to display the calendar of previous, current and next month
Sol: cal -3
4. Give command to display full week day (e.g. Sunday) using data command
Sol: date “+%A”
Exercise:
1. what is output of following commands?
a. $cal 04 2019
b. $ date”+Today’s information: %D and %B”; cal
c. $date “+My clock is showing %H hours, %M minutes and %S seconds”
d. $cal -3
e. $cal -5
f. $cal -2000
2. Give the syntax of commands for displaying the output (use date)
i. This is ……………….. month of the year ……….. (Abbreviations for month and 4-digit year)
ii. This is the ……..’th day of this year
22
Program: Computer Engineering
Experiment No. 03
Title of Experiment Work with multiple Linux terminals and basic
commands: who, who am I, login, passwd, su, pwd
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands
23
Practical Significance: Work with terminal environment to know about users and set their security. It
includes current status of all the users like details about all the users who accesses the terminal for
particular duration and path of directory.
Theoretical Background:
Command Description
who It is used to display who are the users connected to out computer currently.
who am i Display the details of the current working directory.
login Prompt; enter user name
passwd Sets password for users
su (sudo) Provides super user privileges
pwd To print the complete path of the current working directory.
Proposition-3: login
If the user has a password login print password. If password is correct then it allows to enter in login
user is successfully logged into the Unix system.
Only those persons who maintain on “account” with the computer system can use the Unix system.
This list of account is maintained separately in the computer. Ask the administrator of the system to
open an account for you. You start an allotted terminal when you see the following message on the
screen
login:
login: vijay <enter>
if a password has been allotted to you the system will flash the following message.
password:
After confirm password it displays $ prompt. The $ prompt (currency symbol) is the system prompt,
which indicate to the user that some user is logged in and that the system is ready to accept any
command from him. Some of system displays different prompts – the % or # for instance.
25
The pwd command resembles the cd command of MS-DOS when used without argument. Thus pwd
tells you that your current directory is /usr/kumar, you can refer to a sub directory progs, either as
/usr/kumar/progs or simply as progs.
26
Program: Computer Engineering
Experiment No. 04
Title of Experiment a) Use operating services, Run commands to start
stop and restart the specified service in Linux
Resources required Hardware: PC Software: Ubuntu
Objectives Understand the use of basic purpose commands for
services
27
Practical significance: The purpose of computer systems is to allow the user to execute programs. So
the operating systems provides an environment where the user can conveniently run programs. The
user does not have to worry about the memory allocation or multitasking or anything. These things
are taken care of by the operating system.
29
Q. What is difference between GUI and CLI
Sol:
Command Line Interface Graphical User Interface
It is a text-based interface used to interact with It is a visual-based interface which features the
software and operating system by typing use of graphic images, including Windows,
commands into the interface and receive a Icons, and Menus.
response in the same way.
CLI is faster and difficult to use than GUI. GUI is slower and easier to use than CLI.
CLI consumes low memory. It consumes high memory.
Not much flexible. GUI is more flexible.
Commands need to be remembered to be able Commands need not be remembered as they
to type and execute them. can be executed by simply clicking on icons.
CLI is less user friendly. GUI is more user friendly.
Examples: DOS, Unix etc. Example: Windows, Linux etc.
Exercise:
1. What are system calls provided by file management
Sol: file related system call:
Create file, Delete file
Open a file, Close a file
Create directory
Read, Write, Reposition
Get file attributes, Set file attributes
Create a link
Change working directory
30
3. What are system component of operating system
Sol:
Process management
Memory management
I/O management
File management
Communication
Protection and Security
31
Program: Computer Engineering
Experiment No. 05
Title of Experiment Execute process commands – ps, wait, sleep, exit, kill
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of process related commands.
32
Practical Significance: Process is program in execution. Ps commands is used to manage and to see
the active processes on Unix Operating System. Ps basically means ‘process status’ which is used to
display currently running processes in Unix Operating System.
Theoretical Background:
Command Description
ps Display the characteristics of process.
wait Waits until all background processes are completed and then exits.
sleep 30 Used to execute commands after certain amount of time by sleeping for given
seconds.
exit Used to quit the shell.
kill 0 Used to stop execution of particular process by sending an interrupt signal to
the process.
Proposition-1: ps command
A process is simply an instance of a running program.
The process is said to be born when the program starts execution, and remains alive as long as
the program is active. After the execution of the program is complete, the process is said to
die.
This process also has a name; the name of program being executed.
Unix is multi-tasking system; more than one process can run at a time. Each process is uniquely
identified by a number called the PID (the process identifier ) which is allotted by the kernel
when it is born. This is a number between 0 and 32,767.
The ps command is used to display the characteristics of a process. The command invoked
without options simply lists out the processes associated with a user at a particular terminal:
Syntax: ps [option]
$ ps
PID TTY TIME COMMAND/cmd
30 01 0:03 sh
56 01 0:00 ps
$_
Each line shown the PID, the terminal with which the process is associated, the cumulative processor
time that has been removed since the process has been started and the process name. Your login shell
has PID number 30. The ps command itself is an instance of a process identified by PID number 56.
PS command Options
Parameter Description
-a Displays all processes except session headers and processes without a terminal.
-c Displays additional scheduler information about the process.
-d Displays all processes except session headers.
-e Displays all processes.
-f Displays a full format listing.
-j Displays job information.
-l Displays a long listing.
-w Use wide output format, for unlimited width displays
-y Don’t show process flags.
-A Displays all processes.
-F Use extra full output.
33
-H Display processes in a hierarchical format (showing parent processes).
-L Displays process threads
-M Display security information about the process.
-N Displays the opposite of the specified parameters.
-U userlist Displays processes owned by a userid listed in userlist .
-V Display the version of ps
-Z Display the security context information.
The ps command by default does not provide details about the ancestry of a process. To get those you
have to use the –f (full) option:
$ ps -f
UID PID PPID C STIME TTY TIME COMMAND
Kumar 30 1 0 11:18:08 01 0:03 -sh
Kumar 61 30 13 11:24:01 01 0:00 ps -f
$_
The full listing generates eight attributes of a process.
UID: User ID
PID: The process ID of the process
PPID:The PPID (parent PID) is the PID number of the parent process that spawned this process.
Login shell has PID number 1610 and PPID number 1603. Thus the shell was set up by a system
process having a PID number 1.
C: Indicates the amount of CPU time consumed by the process.
STIME: start of process time.
TTY: The terminal device from which the process was launched
TIME: The cumulative CPU time required to run the process
CMD: The name of the program that was started
The –u (user) option lets you know the activities of any user at any time.
$ ps –u Vijay
PID TTY TIME COMMAND
31 pts/2 0:02 sh
59 pts/2 0:00 grep
60 pts/2 0:16 sort
$_
you also combine the –f and –u options:
The –a (all) option lists out the processes of all users:
$ ps –a
PID TTY TIME CMD
1718 pts/0 00:00:00 ps
161 pts/1 00:00:02 sh
354 pts/2 00:00:12 grep
246 pts/1 00:00:37 sh
360 pts/2 00:00:01 ps
439 pts/1 00:00:00 sh
440 pts/3 00:00:01 awk
$_
$ ps –p 533
PID TTY TIME COMMAND
533 pts/1 0:01 vi
34
$ ps –l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 1610 1603 8 80 0 - 1858 wait pts/0 00:00:00 bash
0 R 1000 1665 1610 0 80 0 - 1193 - pts/0 00:00:00 ps
$_
Attributes of –l options
F: System flags assigned to the process by the kernel.
S: The state of the process (O = running on processor; S = sleeping; I=idle process; X: process
waiting for memory; R = runnable, waiting to run; Z = zombie, process terminated but parent
not available; T = process stopped)
UID: The user responsible for launching the process
PID: The process ID of the process
PPID: The PID of the parent process (if a process is started by another process)
C: Processor utilization over the lifetime of the process
PRI: PRI shows the priority with which the process is running. (higher numbers mean lower
priority)
NI: The nice value, which is used for determining priorities
ADDR: ADDR shows the memory or disk address of the process.
SZ: The size of process is memory is indicated by the SZ column.
WCHAN: When process is executed, it may have to wait for system resources which are not yet
available. This indication is shown under WCHAN for running processes this column is blank.
TTY: The terminal device from which the process was launched
TIME: The cumulative CPU time required to run the process
CMD: The name of the program that was started
35
Proposition-5: kill command
The kill command will kill a process using the kill signal and PID given by the user.
The kill command allows you to send signals to processes based on their process ID (PID).
The command uses one or more PID numbers as its arguments.
Syntax:
kill [signal] PID
Kill pid1 pid2 ….
Exercise:
$ sleep 30; date
$ echo $$
$ sleep 60; banner “Goog”
36
Program: Computer Engineering
Experiment No. 06
Title of Experiment Execute file and directory manipulation commands:
ls, rm, mv, cp, join, split, cat, head, tail, touch
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of file manipulation commands.
37
Practical Significance
Basically the operating performs I Unix/Linux are done on prompt/terminal which is not stored
anywhere. But most of the commands are written to store the information. One way is to store the
information in a file. Various operations that can be performed on a file are create, open, read, write,
move, close and rename.
Proposition-1: ls command
The ls command displays a list of files which are available in directory.
$ ls <enter>
chap1
chap2
chap3
$_
Options of ls commands :
Option Description
-a Displays all files including ., .. and hidden files
-A Displays all but not . and .
-C List entries by column
-d List directory entries instead of contents
-l Use ling listing format
-r Sort in reverse order
-R List subdirectory recursively
-s Prints size of each file in blocks
-S Sort by file size
-t Sort by modification time
-u Sort by access time
-V Sort by version
-1 List one file per line
-X List in column format with row wise sorting
-F Classifies files, executables, directories
-i Shows inode number of a file
Example:
$ ls –l chap1
-rwxr--r-- 1 user1 group1 712 jan 20 10:30 chap1
(file mode) (no. of links) (file owner) (group name) (size of file) (date& time) (file name)
Proposition-2: rm command
Deleting files – The rm command:
Files can be deleted with rm (remove). The following command deletes the first three chapters of the
text.
$ rm chap1 chap2 chap3
$_
rm won’t normally remove a directory, but it can remove files from one.
$ rm progs/chap1 progs/chap2
you can remove two chapters from progs directory without having to “cd” to it.
You can easily delete all files in directory by
38
$ rm *
$_
MS-DOS users beware! When you delete files in this fashion, the system won’t prompt you with the
message “Are you sure?” or “all files in directory will be deleted?” before removing the files. The $
prompt will return silently, suggesting that the work has been done. When rm is invoked with
options, different things start happing. The –i (interactive) option makes the command prompt the
user with each filename and a?, before acting on it:
$ rm –i chap1 chap2 chap3
chap1 : ? y
chap2 : ? n
chap3 : ? n
$_
if you press ‘y’ then the file will be deleted.
Option Description
-f Ignore non-existant files, and never prompt before removing.
-i Prompt before every removal.
-I Prompt once before removing more than three files, or when removing recursively.
Less intrusive than -i, while still giving protection against most mistakes.
-r Remove directories and their contents recursively.
Proposition-3: mv command
The mv (move) command simply renames a file or a group of files. mv does not create a copy of file,
it merely renames it.
To rename the file chap1 to man1
$ mv chap1 man1
$_
$ mv chap1 chap2 chap3 progs
$_
moves the files chap1, chap2 and chap3 to the progs directory. mv can be used to rename a
directory.
Option Description
-f Do not prompt before overwriting existing files.
-i Prompt before overwriting each existing destination file, regardless of the
file's permissions.
-n Do not overwrite any existing file.
Proposition-4: cp command
Coping a File – The cp command:
The cp (copy) command copies a file or a group of files.
If the command contains two file names, then it copies the contents of first file to the second
file. If the second file doesn’t exist, then first is creates one and content is copied to it, but if it
existed then it is simply overwritten without any warning.
Similar to copy command of MS-DOS, cp creates an exact images of the file on the disk with a
different name. To copy the file chap1 to unit1 you use
$ cp chap1 unit1
$_
39
If there is only one file to be copied, then the destination can be either an ordinary or a directory file.
For example to copy file chap1 to directory progs.
$ cp chap1 progs/units
$_
If there are groups of files to be copied, then you specify command line: the syntax requires the
destination file to be a directory and copies the files into directory.
$ cp chap1 chap2 chap3 progs
file1 has 12 lines is split into three files xaa, xab, xac of 4 lines each or
$ split –4 file1 num
The file “file1” of 12 lines is split into three files numaa, numab, numac of 4 lines each.
40
Proposition-7: cat command
Displaying and Creating files- The cat command
The cat command like the type command of MS-DOS, cat is used to display the contents of file. To
do that for the file dept.lst, simply specify the filename as the argument:
$ cat dept.lst
01 | computer | 60
02 | information | 40
03 | electronics | 60
$_
41
Proposition-9: tail command
Displaying the end of a file - The tail command
The tail command displays the end of the file. If no line count is given, tail displays the last ten lines
of the file.
$ tail emp.lst
$_
syntax : $ tail [ + - ] number [file]
option Description
-n Display specified number of lines
+n Display all lines beginning from nth line
$ tail -20 temp It displays last 20 lines of a file
$ tail +20 temp it displays lines from line number 20 to end of file
Exercise:
1. Create three files a1 a2 a3
2. Display all file names which starts with ‘a’ and end with ‘y’
3. Enlist all the files beginning with ‘m’ and ending with any range of 1 to 5
4. Show the contents of the files whose file names contains exactly two characters
5. How many lines will be displayed with head command if number is not specified
6. Display inodes of two files
7. Rename the file chapter1 to lesson1
8. ls a*n
9. ls s?
10. cat abc >> xyz
42
Program: Computer Engineering
Experiment No. 07
Title of Experiment Execute file and directory manipulation commands:
diff, comm, pr, chmod, mkdir, rmdir, cd, pwd, dir,
cmp. (use wild card characters)
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of file manipulation commands.
43
Practical Significance
Data and programs are stored in files. Directory is just a file that contains other files (or directories).
Unix uses a hierarchical structure for organizing files and directories. This structure is called as a
directory tree. The tree has a single root node, slash character(/).
All files in UNIX are “related” to one another. The file system in UNIX is a collection of all these related
files organized in a hierarchical (an inverted tree) structure. This system has been adopted by MS-DOS
and is visually represented by:
The top is called root, but is represented by a / (backslash). Root is actually a directory file, and it has
a number of sub-directories (or branches) under it. Home, bin and usr are directories directly under
root while a second mthomas and stu1 are sub directories under home. Every file apart from root must
have a parent home directory is a parent of stu1, while root is parent of home, bin usr, and the
grandparent of stu1. Once the relationship between various files is established in this manner, UNIX
provides a simple mechanism of accessing a file. The login directory mthomas can also be specified as
/home/mthomas. It is called a pathname for the directory file mthomas. Every pathname consists of
a sequence of directory names separated by /’s. The tree like structure enables you to create as many
directories as you wish so that one directory does not need to contain too many files. This permits you
to use two files with the same name but in different directories, so that they will have different
pathnames. Thus the file /home/mthomas/class_stuff/a1.c is different from the file
/home/mthomas/bin/a1.c
Most Unix commands use files whether you should use the command cat xyz.c to display the
contents of the file. The directory where you are placed or located is known as the current directory.
The directories shown directly under root are normally found in every UNIX system. The directories
/bin, /dev, /etc and /lib are system directories and the other directories like /tmp and /usr are meant
for the users.
The commonly used UNIX commands like who. cat, wc, etc are stored in the /bin and /usr/bin
directories and made available to every user. /dev contains the device files of all hardware devices.
/etc contains those utilities mostly used by the system administrator. /tmp is used by some UNIX
utilities (especially vi) as well as by a user to store temporary files. Finally, the /usr directory contains
all the files created by a user including his login directory.
The directories in UNIX operating system have specific purposes and generally hold the same types of
information for easily locating files. Following are the directories that exist on the major versions of
UNIX:
44
Directory Description
/ This is the root directory which should contain only the directories needed at the top
level of the file structure.
/bin This is where the executable files are located. They are available to all user.
/dev These are device drivers.
/etc Supervisor directory commands, configuration files, disk configuration files, valid user
lists, groups, ethernet, hosts, where to send critical messages.
/lib Contains shared library files and sometimes other kernel-related files.
/home Contains the home directory for users and other accounts.
/mnt Used to mount other temporary file systems, such as cdrom and floppy for the CD-
ROM drive and floppy diskette drive, respectively
/proc Contains all processes marked as a file by process number or other information that is
dynamic to the system.
/boot Contains files for booting the system.
/sbin Contains binary (executable) files, usually for system administration. For example fdisk
and ifconfig utlities.
/tmp Holds temporary files used between system boots
/usr Used for miscellaneous purposes, or can be used by many users. Includes
administrative commands, shared files, library files, and others
/var Typically contains variable-length files such as log and print files and any other type of
file that may contain a variable amount of data
/kernel Contains kernel files
Proposition-2: cd command
Changing Directories – The cd command
You can move around in the file system by using the cd (change directory) command. It changes the
current directory to the directory to the directory specified as the argument.
Syntax: cd <directory name>
$ pwd
/usr/kumar
$ cd progs
$ pwd
/usr/kumar/progs
$_
45
Proposition-3: rmdir command
Removing a Directory – The rmdir command:
The rmdir (remove directory) command removes or deletes directories.
Syntax: rmdir <directory name>
$ rmdir lesson
$_
you can not delete a directory unless it is empty. The three directories and the sub directories that
were just created with mkdir can be removed by using rmdir with a reversed set of arguments.
$ rmdir lesson/chap1 lesson/chap2 lesson
47
To drop a particular column simply use its column number with the –sign. Thus to select only those
lines which are not common to both files you should exclude the third column from the output:
The two files are compared byte by byte and the location of the first mismatch is echoed to the
screen. If the two files are identical then cmp displays no message, but simply returns the $ prompt.
The –l (list) option gives detailed list of the byte number and the differing bytes in octal for each
character that differs in both the files.
$ cat file1
abcd
xyz
$ cat file2
abed
wxy
$_
Proposition-9: pr command
File formatting and printing commands-pr command:
The pr command prepares a file for printing by adding suitable headers, footers and formatted text.
$ pr dept.lst
May 11 10:17 1990 dept.lst page 1
48
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
pr adds five lines of margin at the top and five lines at the bottom of the five lines at the top one is
reserved for header information. The header shows the date and time of the last modification of the
file along with the filename and page number.
$ pr dept.lst | lp
request id is 334
$_
pr also accepts input from standard input which can also be redirected to originate from a file.
$ pr < dept.lst
May 11 10:17 1990 dept.lst page 1
01 | 2233 | shulka a.k. | g.m. | sales | 6000
02 | 9876 | Sharma | director | production | 7000
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
by default the page size is 66 lines which is the size used in U.S.A. however continuous stationary is
also available with 72 lines on each page. Use –l (length) option along with a numeric argument to
specify that:
$ pr –l 72 chap1
The option –l 72 sets the page to 72 lines of which to lines (5+5) will be used by the top and bottom
margin leaving 62 for the actual contents of the file. The option –w (width) which overrides the
default width of 72 characters.
$ pr –w 132 chap1
you can also frame your own header instead of displaying filename by using –h (header) option:
49
03 | 5678 | charkrobarty | d.g.m. | marketing | 6000
04 | 2365 | sengupta | director | personnal | 7800
05 | 5423 | gupta n.k. | chairman | admin | 5400
<blank lines>
$_
The –k option (where k is any integer) produces output in more than one column across the page.
$ pr –3 dept.lst
May 11 10:17 1990 code List page 1
01 | shulka a.k. 02 | Sharma 03 | charkrobarty
04 | sengupta 05 | gupta n.k. 06 | patel
<blank lines>
$_
The –d (double) option double spaces the output i.e. it adds a blank line for every line read.
$ pr –172 –w80 –n –d dept.lst
The –m (merge) option allows you to merge two or more files simultaneously so that they appear
pasted laterally.
$ pr –m dept.lst sal.lst
you can omit header and footer with the –t option.
$ pr –m –n –t dept.lst sal.lst
50
Absolute Permission (The Octal Notation):
In absolute permission, each type of permission is assigned a number. This format requires specifying
permissions using three octal numbers ranging from 0 to 7. The octal code can be one to three digits
long. The first, second, third digits set the “user” “group” “other” user permissions respectively. The
integer used in each position dictates the permission for the file.
Concept Diagram:
Exercise
1. Create the following structure
51
2. How to see directories
3. What is default set of permissions given by the system to the directory
4. Assign all the permissions to your directory for all the users using symbolic and octal method
5. What is difference between comm and cmp command
6. What are the permissions assigned to file after execution of following commands
a. $ chmod 700 abc
b. $ chmod u+rwx,go-rx file1
c. $ chmod 536 xyz
d. $ chmod ugo=r abc
e. $ chmod ugo+r abc
7. Write commands to assign following permissions to the file “abc” using symbolic method and octal
method
a. _ _ _ _ _ _ _ _ _
b. _ rwr_xr_ _
c. rwxrwxrwx
d. r_ _ r_ _ _ _ _
e. rwxr_xr_x
f. rwxrw_rw_
52
Program: Computer Engineering
Experiment No. 08
Title of Experiment Execute text processing tr, wc, cut, paste, spell, sort,
grep, more
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of text processing commands.
53
Practical Significance: There are many text processing commands. A filter is a program that takes a
flow of data from the standard input, processes or filters it and send the result to standard output.
Cut, wc, tr, sort, grep are all simple filters.
Proposition-1: tr command
Translating characters - The tr command
Syntax : tr <option> <expressions1> <expression2> <standard input>
The first difference that this command takes only the standard input as the source of its data; it does
not take a filename as its argument. When invoked without options, it translates each character in
expression1 to its mapped counterpart in expressions2. The first character in the first expression is
replaced by the first character in the second expression and similarly for the other characters.
The following tr command is used to convert the lower case to upper case
$tr
Operating system
OPERATING SYSTEM
The following command will also convert lower case to upper case
$ tr [:lower:] [:upper:]
ops
OPS
More Examples
1) $ tr “[a-z]” “[A-Z]” < xyz or ( ‘a-z’ ‘A-Z’)
$ tr “[:lower:]” “[:upper:]” < xyz
used to fold all lowercase characters to uppercase in the file xyz
2) $ tr “[a-d]” “[0-3]” < xyz
first four lowercase alphabets are substituted with numbers from 0-3
3) $ tr –s “ “ < xyz
squeezes all occurrences of blank spaces to one space in the file xyz
4) $ tr –d “e” < xyz
deletes all occurrences of e from file xyz
5) $ tr –cd “e” < xyz
all characters other than e would be deleted from the file xyz
6) $ tr –c “[a-z]” “[\n]” < file1
outputs a list of all words in file1, one per line in file2
Proposition-2: wc command
The wc (word count) command in Unix/Linux operating system is used to find out number of
lines, words and characters in a file.
Unix features a universal word counting program. The command name is in fact a misnomer: it
counts lines, words and characters depending on the options used. It takes one or more
filenames as its argument and displays a four columnar output.
Syntax: wc [-l-w-c] <filename>
Options Description
-l Counts only number of lines
-w Counts only number of words
-c Counts only number of characters
54
Example:
$ cat data1
wc command counts characters,
words and lines
$_
$ wc data1
2 7 45 data1
$_
we counts 2 lines, 7 words, 45 characters. A line is group of characters. A word is group of characters
not containing a space, tab or newline. A character is smallest unit of information and includes all
spaces, tabs and newlines. The filename has also been shown in the fourth column. wc offers three
options to make a specific count. –1 counts only number of lines, -w and –c options counts words
and characters respectively.
$ wc –1 data
2 data
$ wc –w data
7 data
$ wc –c data
45 data
$_
When wc is used with multiple filenames, it produce a line for each file as well as total count.
$ wc chap1 chap2 chap3
305 4058 23179 chap1
550 4732 28132 chap2
377 4500 25221 chap3
1232 13290 76532 total
$_
55
$ cut –c 6-22, 24-32 shortlist
2233 shulka a.k.
9876 Sharma
5678 charkrobarty
2365 sengupta
5423 gupta n.k.
$_
column numbers must immediately follow the option.
$ cut –f 1, 5 shortlist
2233 | 6000
9876 | 7000
5678 | 6000
2365 | 7800
5423 | 5400
option Function
-f Displays the fields specified
-c Cutting of columns i.e. character by character
-d Specifies the column delimiter
56
Proposition-5: spell command
spell is a spell-checking program which scans a text file for misspelled words, and prints each
misspelled word on its own line. spell is a very minimalistic spell-checking program, based on the
original UNIX spell checker. It reads the contents of file FILE, word for word, checking them against its
dictionary. If a word does not correspond with any of spell's dictionary words, the word is printed.
Syntax: spell [OPTIONS] FILE
Options:
-n Print line numbers.
-o Print file names.
$ sort –n numfile
2
4
10
27
$_
Duplicate lines are removed with the –u (unique) option.
57
Proposition-7: grep command
Search for a pattern in a file, Search for the given string in a file
The grep command allows you to search one file or multiple files for lines that contain a
pattern.
Grep means global regular expression printer.
Exit status is 0 if matches were found, 1 if no matches were found, and 2 if errors occurred.
Example:
$ cat student
Geeta 12123 female thane
Mahesh 24321 male mumbai
Vijay 43231 male mumbai
Ajay 54252 male thane
Sanjay 65421 male thane
Seeta 87652 female mumbai
$_
To search for Sanjay
$ grep sanjay student
Sanjay 65421 male thane
$_
58
Example:
“people” The word people anywhere on a line. $ grep “people” temp
“^people” The word people at the start of a line. $ grep “^people” temp
“people$” The word people at the end of a line. $ grep “people$” temp
“^people$” A single line with the word people in it. $ grep “^people$” temp
“a*ll” Asterisk matches zero or more occurrences $ grep “a*ll” temp
of any patterns preceding it in the file.
Exercise:
1. Write Commands for:
a. counting number of words in the “data.txt”
b. counting number of lines in “data.txt”
c. counting all characters in “data.txt”
2. Give applications of paste command
3. What are the options of wc command
4. What are different types of filters used in Linux
5. Try the commands and write output with its meaning
a. tr “[a-f]” “[0-5]” <emp
b. tr –s “ “ < emp
c. tr –d “f” < emp
59
Program: Computer Engineering
Experiment No. 09
Title of Experiment Use vi editor and perform all editor commands
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of vi editor and perform
commands.
60
Practical Significance: There are many ways to edit files in Unix. Editing files using the screen
oriented text editor vi is one of the best ways. This editor enables you to edit lines in context with
other lines in the file. An improved version of the vi editor which is called the VIM has also been
made available now, VIM stands for Vi IMproved
A vi session begins by invoking the command vi with or without a filename:
$ vi filename ( $ vi temp)
you are presented with a full empty screen, each line beginning with a ~ (tidle) for text editing, vi uses
24 of the 25 lines that are normally available in a terminal. The last line is reserved for ex commands.
The filename appears in this line with the message “temp” [new file]. The cursor is positioned at top
left hand corner of the screen.
Three modes in which vi works:
Input mode = where any key depressed is entered as text.
Command mode = where key are used as commands to act on text.
Ex mode = where ex commands can be entered in the last line to act on text.
You can use the backspace key to erase any inserted text, one character at a time. You can also effect
a speedier movement by using <control-u> to move back to the beginning of a word. The input mode
is terminated by pressing the <Esc> key, which takes you back to the command mode.
There are other methods of inputting text. To append text to the right of the cursor position use ‘a’
followed by the text you wish to key in. you can append several lines of text in this way. ‘I’ inserts text
at the beginning of a line, while ‘A’ appends text at the end of a line. You can also open a new line by
positioning the cursor at any point in a line and pressing ‘o’. This inserts an empty line below the
current line. ‘O’ also opens a line but above the current line.
Text is replaced with the r, R, s and S keys. To replace one single character by another you
should use ‘r’. To replace more than a single character use ‘R’ followed by the text. Existing text will be
overwritten as the cursor moves forward. The ‘S’ character replaces the single character under the
cursor with existing text; irrespective of its length ‘S’ replaces the entire line.
61
Input mode Commands:
Command Function
i Inserts text to left of cursor
I Inserts text at beginning of line
a Appends text to right of cursor
A Appends text at end of line
o Opens line below
O Opens line above
rch Replaces single character under cursor with char ch
R Replaces text from cursor to right
s Replaces single character under cursor with any number of characters
S Replaces entire line
To switch to the command mode from input mode by pressing the <Esc> key.
Deletion: The simplest text deletion is achieved with the ‘x’ command. This command deletes the
character under the cursor. Move the cursor to the character that needs to be deleted and then press
‘x’. A repeat factor applies so 4x deletes the current character as well as three characters from the
right. Entire lines are removed by using the ‘dd’ command move the cursor to any line and then press
‘dd’ once again, you can use a repeat factor. Thus 6dd deletes the current line and following five.
Command Description
x Deletes the character under the cursor location
X Deletes the character before the cursor location
Dw Deletes from the current cursor location to the next word
d^ Deletes from the current cursor position to the beginning of the line
d$ Deletes from the current cursor position to the end of the line
D Deletes from the cursor position to the end of the current line
dd Deletes the line the cursor is on
62
of a word use ‘b’. While to move forward to the end of a word use ‘e’. To move to start of the next
word use ‘w’. A repeat factor speeds up cursor movement along a line.
Ex. 5b takes the cursor five words back while 3w takes the cursor three words forward. With the ‘^’
taking the cursor to the beginning of the first word in a line use ‘o’ or ‘l’. The $ plays the usual role here
and it takes the cursor to the end of the line.
‘?’ pattern <enter> searches backward for the most previous instance of the pattern. Thus the symbol
‘/’ searches in the forward direction while ‘?’ reverse the search. For repeating a search in the direction
in which the precious search was made with ‘/’ or ‘?’ use n and for repeating the search in the reverse
direction use ‘N’.
Search and repeat command:
63
• /pat = Searches forward for pattern pat.
• ?pat = Searches backward for pattern pat.
• n = Repeat search in same direction along which the previous search was made.
• N = Repeats search in a direction opposite to that along with the previous search was made.
• fch = Moves cursor forward to first occurrence of character ch in the ; current line.
• ; = Repeats search in same direction along which the previous search was made with F or t.
• , = Repeats search in a direction opposite to that along which the previous search was made
with F or t.
Joining lines:
Lines can be joined with the J command 4j joins four lines starting with the current line.
Operators:
Text Direction: ‘d’ operator use for delete characters and lines, the ‘d’ operator with the $ to delete
from the cursor position to the end of a line. Use the sequence d$. The command to delete a word
should be equally simple use dw. To delete a complete line double the operator dd.
3dw deletes three words and 5dd deletes five lines, starting with the current line. The deleted text is
placed in a different location with the p and P(put) commands.
Changing Text: Text can be changed with the c operator dw deletes a word while cw changes the
words. To change text from the present cursor position up to the end of a line use c$ or c. To change
entire lines use cc.
Command Description
cc Removes the contents of the line, leaving you in insert mode
cw Changes the word the cursor is on from the cursor to the lowercase w end of the
word
r Replace the character under the cursor. Vi returns to the command mode after
the replacement is entered
R Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting
s Replaces the current character with the character you type. Afterward you are
left in the insert mode
S Deletes the line the cursor is on and replaces it with the new text. Afterword the
new text is entered, vi remains in the insert mode.
Yanking Text: you can copy lines or words from one place and then you can paste them at another
place. The y operator yanks (or copies) text to yank five lines of text, move the cursor to the first of
these and press 5yy or 5y next move the cursor to the new location and press p or P.
Copy and paste commands
Command Description
yy Copies the current line
yw- Copies the current word from the character the lowercase w cursor is on, until
the end of the word
p Puts the copied text after the cursor
P Puts the yanked text before the cursor
64
Ex mode commands for file handling:
Press Esc key and then (:) colon to enter ex-mode commands. A colon is displayed at the left hand
corner of the last line on you screen
Command Function
:w Saves file and remains in editing mode
:w note1 Creates file note1 and writes buffer contents to it
:w >> note1 Appends buffer contents to file note1
:x Saves file and quits editing mode
:wq Saves and quits editing mode
:q Quits editing mode without saving
:q! Quits vi cancelling the changes
:e note1 Stops editing current file and edits file note1
:n Edits next file
:sh Escape to Unix shell
Exercise:
1. Write command to save the file
2. Write the command to insert text at the end of line
3. Write a command to delete 10 lines at a time
4. Write a command to move cursor 3 word to the right
5. State the three ways to quit the vi-editor
6. What is effect of: set nu, set ic, set nonu, set noai
7. What is difference between yank and delete
8. What are different modes in Vi editor
65
Program: Computer Engineering
Experiment No. 10
Title of Experiment Write and execute shell script by using following
control statements features: if statement
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script and control
statements.
66
Practical Significance: If is a statement that allows the programmer to make a decision in the program
based on conditions he specified. If the condition is met, the program will execute certain lines of code
otherwise, the program will execute other tasks the programmer specified.
67
Example-1:
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
output:
a is not equal to b
Example:
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Output:
a is not equal to b
68
Syntax: Concept Diagram:
If [ conditional expression1 ]
then
statement1
statement2
.
elif [ conditional expression2 ]
then
statement3
statement4
.
else
statement5
fi
Example:
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
Output:
a is less than b
Programs:
1. Write script for finding greatest number among given three number
#!/bin/bash
echo "enter first number"
read first
echo "enter second number"
read sec
echo "enter third number"
read third
if [ $first -gt $sec ] ; then
if [ $first -gt $third ] ; then
echo -e " $first is greatest number "
else
echo -e " $third is greatest number "
fi
else
if [ $sec -gt $third ] ; then
echo -e " $sec is greatest number "
else
echo -e " $third is greatest number "
fi
fi
70
3. Write a shell program to check whether the given number is less than 10 or not?
$cat check
#!/bin/bash
#check number
echo “enter any no. from 1 to 10”
read number
if [ $number –lt 10 ]
then echo ”small number”
else
echo “large number”
fi
output:
$./check
enter any no. from 1 to 10
5
small number
$./check
enter any no. from 1 to 10
15
large number
4. Write a shell program to checks the category of user on the basis of age.
$ cat age
#!/bin/bash
echo “Enter your age”
read age
if [$age –lt 13]
then echo “A Child”
elif [$age –le 19]
then echo “Teenage”
elif [$age –lt 30]
then echo”Youth”
elif [$age –lt 50]
then echo “Middle Age”
else echo “Old Age”
fi
$_
output:
Enter your age
15
Teenage
71
else
echo "Number is odd"
fi
output:
Enter a number
4
Number is even
Enter a number
5
Number is odd
72
Program: Computer Engineering
Experiment No. 11
Title of Experiment Write and execute shell script by using following
control statements features: for, exit, break, continue
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script and control
statements.
73
Practical Significance: The for loops iterate through a set of values until the list is exhausted. In simple
term the for loop operates on lists of items. It repeats a set of commands for every item in a list.
Output:
1
2
3
4
5
74
Here n specifies the nth enclosing loop to the exit from.
Example:
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
output:
0
1
2
3
4
5
75
Proposition-5: exit statement
exit command in linux is used to exit the shell where it is currently running. It takes one more
parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns
the status of last command that is executed.
Syntax: exit [n]
Example:
$ cat test
#!/bin/bash
# while command test
var1=0
while [ $var1 -le 10 ]
do
echo $var1
var1=$[ $var1 + 1 ]
done
$ ./test
1
2
3
4
5
6
7
8
9
10
$
76
Proposition-7: until statement
The until loop is very similar to the while loop, except that the loop executes until the test-command
executes successfully. As long as this command fails, the loop continues.
Syntax:
until test commands
do
other commands
done
Example:
$ cat test10
#!/bin/bash
# until command test
var1=0
until [ $var1 -ge 10 ]
do
echo $var1
var1=$[ $var1 + 1 ]
done
$ ./test10
1
2
3
4
5
6
7
8
9
10
$
77
*) default
commands;;
esac
Concept Diagram:
Example-1:
#!/bin/sh
FRUIT="orange"
case "$FRUIT" in
"apple") echo "It’s an Apple."
;;
"banana") echo "It’s a banana."
;;
"orange") echo "It’s an Orange."
;;
esac
output:
It’s an Orange.
Example-2:
echo “enter no”
read no
case “no” in
0) echo “Zero”;;
1) echo “One”;;
2) echo “Two”;;
|
9) echo “Nine”;;
*) echo “Invalid Argument”;;
Esac
78
Programs
1. Write a shell program to copy the content of one file into another file
$ cat test
#!/bin/bash
echo “enter source and target filename”
read source target
if cp $source $target
then
echo “file copied successfully”
else
echo “file copy is failed”
fi
3. Write a shell script to find out the factorial of the given number.
i=1
f=1
echo " Enter the number"
read n
while [ $i -le $n ]
do
f=`expr $f \* $i`
i=`expr $i + 1`
done
echo FACTORIAL = $f
output:
Enter the number
5
FACTORIAL=120
79
4. Write a shell script to find out whether the given number is prime number or not.
echo Enter the number
read n
i=1
c=0
while [ $n -ge $i ]
do
if [ `expr $n % $i` -eq 0 ]
then
c=`expr $c + 1`
fi
i=`expr $i + 1`
done
if [ $c -eq 2 ]
then
echo Prime Number
else
echo Not Prime number
fi
output
Enter the number
5
Prime number
Enter the number
4
Not Prime number
5. Write a shell script to find out sum of the digits of the given number.
sum=0
echo " Enter the number"
read n
while [ $n -gt 0 ]
do
temp=`expr $n % 10`
sum=`expr $sum + $temp`
n=`expr $n / 10`
done
echo $sum
output
Enter the number
234
9
80
echo “5.Free disk space”
echo “6.Quit to Unix”
echo “Enter you choice”
read ch
case $ch in
1) ls –l;;
2) ps –f;;
3) date ;;
4) who;;
5) df;;
6) exit;;
esac
8. Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.
#cat rev
#!/bin/bash
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find reverse of given number"
echo " For eg. $0 123, I will print 321"
exit 1
fi
n=$1
rev=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse number is $rev"
output
#./rev 123
Reverse number is321
81
9. Write a shell script to find out whether the given string is Palindrome or not using command line
argument
#cat palin
#!/bin/bash
s=`echo $1 | wc -c`
while [ $s -gt 0 ]
do
temp=`echo $1 | cut -c $s`
s=`expr $s - 1`
temp1="$temp1$temp"
done
echo "Reverse string is $temp1"
if [ $1 = $temp1 ]
then
echo “The given string is palindrome”
else
echo “ Not palindrome”
fi
output
#./palin madam
Reverse string is madam
The given string is palindrome
82
11. Write a shell script to generate a multiplication table
echo Multiplication Table:
echo Which table do you want ? (Give Number):
read num
iter=1
while [ $num –le 5 -a $iter -le 10 ]
do
res=`expr $num \* $iter`
echo $num “*” $iter “=” $res
iter=`expr $iter + 1`
done
output:
Multiplication Table:
Which table do you want ? (Give Number):
3
3*1=3
3*2=6
3*3=9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
13. Write shell script using for loop to print the following patterns on screen
Pattern-1
for (( i=1; i<=5; i++ ))
do
for (( j=1; j<=i; j++ ))
do
echo -n "$i"
done
echo ""
done
output:
1
22
333
4444
55555
Exercise:
State the difference between iteration and recursion
Write a shell script to find largest number from three numbers.
Write script to print Even numbers.
Write a shell script to perform arithmetic operations using case statement.
Execute shell script by considering example like printing table of given number by for loop
Write a shell script to display tables of 2 to 10 numbers (like 2*1=2)
Write shell script to print following output
1 * * ****
12 ** * ***
123 *** * **
1234 **** * *
12345 *****
*
84
Program: Computer Engineering
Experiment No. 12
Title of Experiment Write shell script to find out whether given file exists
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script for perform
permission on file.
85
Practical Significance: In Unix data and programs are stored in files. These are organized in directories.
In a simple way, a directory is just a file that contains other files (or directories).
The test command allows you to test the status of files and directories on the Linux file system. These
conditions give you the ability to check files in your file system within your shell scripts, and they are
often used in scripts that access files.
Programs
1. Write a shell script to check whether a given argument is a directory or not
$ cat check
#!/bin/bash
# Script to check for directory files
read f1
if [ –d $f1]
then echo “ $f1 is a directory”
ls
else mkdir $f1
fi
86
2. Write a shell script to check whether a given argument is a file or not
$ cat check
#!/bin/bash
#file test
echo “enter file name”
read file
if [ -f $file ]
then echo “file is exit”
else echo “$file is not a file”
fi
Exercise:
What are file test options with its meaning?
Write a shell script which accept input as a file or directory and displays message whether it is
file or directory.
Write a shell script which displays list of all directories in your home directory.
87
Program: Computer Engineering
Experiment No. 13
Title of Experiment Write shell script to find out whether file has read,
write and execute permissions
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and use of shell script for perform
permission on file.
88
Practical Significance: In Unix files come with permissions, a way to decide who can read, write or
execute a file. these permissions are divided into three parts: owner of the file, those for the group to
which the owner belongs and then permissions for all the other users from the point of view of what
is allowed to do in a file or directory, permissions are for reading, writing and executing.
Comparison Description
-r file Checks if file exists and is readable.
-s file Checks if file exists and is not empty.
-w file Checks if file exists and is writable.
-x file Checks if file exists and is executable.
Exercise:
What are permissions of a file?
How to assign permission to a file?
How to check permissions of all files and directories?
What are the test commands to check the permission of a file?
Write a shell script which displays the list of all executable files in the current working
directory.
Write a shell script which displays a list of all the files in the current working directory which
user has read, write and execute permission.
Write a shell script which accepts a filename and assigns it all the permissions.
89
Program: Computer Engineering
Experiment No. 14
Title of Experiment Write a program to calculate total waiting and
turnaround time of a processes with first come first
serve CPU scheduling algorithms.
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and implement the FCFS Scheduling
algorithms
90
Practical Significance: In multiprogramming systems, the operating system schedules the processes
on the CPU to have the maximum utilization of it and this procedure is called CPU scheduling. The
Operating system uses various scheduling algorithm to schedule the processes. First Come First Serve
(FCFS) scheduling algorithm simply schedules the jobs according to their arrival time.
Questions:
1. Compare SJF, priority and RR
Parameter FCFS algorithm SJF algorithm Priority Algorithm RR Algorithm
Preemption This scheduling This scheduling This scheduling This scheduling
algorithm is non algorithm is algorithm is also algorithm is also
preemptive. preemptive. preemptive. preemptive.
Complexity This is simplest This algorithm is This algorithm is In this scheduling
scheduling difficult to also difficult to algorithm
algorithm. understand and understand. performance
code. heavily depends
91
upon the size of
time quantum.
Allocation In this scheduling In this scheduling This scheduling In this scheduling
algorithm it algorithm CPU is algorithm is based algorithm the
allocates the CPU allocated to the on priority the preemption take
in the order in process with least higher priority job place after a fixed
which the CPU burst time. can run first. interval of time.
processes arrives.
Application This scheduling This scheduling This scheduling This scheduling
algorithm is good algorithm is also algorithm is also algorithm is good
for non interactive good for non good for non for interactive
system. interactive interactive system.
system. system.
Waiting Time In this scheduling In this scheduling In this scheduling
In this scheduling
algorithm the algorithm the algorithm the
algorithm the
Average waiting Average waiting Average waiting Average waiting
time is large. time is small as time is small astime is large as
compare to FCFS compare to FCFS compare to all the
scheduling scheduling three scheduling
algorithm. algorithm. algorithm.
Usability This scheduling In this scheduling This scheduling
In this scheduling
algorithm is never algorithm the algorithm is thealgorithm if the
recommended problem is to sometime quantum size is
whenever know the length of becomes the
large then this
performance is a time for which the biggest cause ofalgorithm become
major issue. CPU is needed by starvation. same as FCFS
the process. algorithm and its
performance
degrade.
Type of This scheduling This scheduling This scheduling This scheduling
System algorithm is algorithm is also algorithm is based algorithm is suitable
suitable for Batch suitable for Batch upon priority. for time sharing
system. system. system.
92
3. Give the reason of problem arises in FCFS
The average waiting time under FCFS policy is generally not minimal and may vary greatly. The FCFS
scheduling algorithm is non-pre-emptive. Once the CPU has been allocated to a process, that process
keeps the CPU until it releases the CPU, either terminating or by requesting I/O.
Disadvantages of FCFS Scheduling:
Average waiting time is very large
FCFS is not an attractive alternative on its own for a single processor system
Another difficulty with FCFS tends to favor processor bound. Processes over I/O bound
processes and may result in inefficient use of both the processor and the I/O devices.
Program Code:
Consider the processes P1, P2, P3, P4 given in the below table, arrives for execution in the same
order, with arrival time 0 and given burst time, find using the FCFS scheduling algorithm.
1. Turnaround time for each process
2. Waiting time for each process
3. Average turnaround time
4. Average waiting time
Process Burst Time
P1 21
P2 6
P3 3
P4 2
‘C’ Code:
#include<stdio.h>
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum 20):");
scanf("%d",&n);
avwt/=i;
avtat/=i;
printf("\n\nAverage Waiting Time:%d",avwt);
printf("\nAverage Turnaround Time:%d",avtat);
return 0;
}
Output:
Enter total number of processes (maximum 20):4
Enter Process Burst Time
P[1]:21
P[2]:6
P[3]:3
P[4]:2
94
Exercise:
1. Solve the problem using FCFS algorithm and preemptive SJF. Find average waiting time and
turnaround time using Gantt chart
Process Arrival Time Burst Time
P1 0 10
P2 1 4
P3 2 14
P4 3 8
2. Calculate average waiting time using RR algorithm for the following set of processes with the
length of the CPU burst time in milliseconds (Time quantum-20ms)
Process Burst Time
P1 12
P2 45
P3 78
P4 90
95
Program: Computer Engineering
Experiment No. 15
Title of Experiment Write a C program to implement FIFO page
replacement algorithm
Resources required Hardware: PC Software: Ubuntu
Objectives Understand and implement the FIFO page
replacement algorithms
96
Practical Significance: When there is a page fault, the referenced page must be loaded. If there is no
available frame in memory, then on page is selected for replacement. If the selected page has been
modified, it must be copied back to disk (swapped out). A page replacement algorithm is needed to
decide which page needs to be replaced when new page comes in.
7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Questions:
1. What is page hit?
When we want to load the page on the memory, and the page is already available on memory, then
it is called page hit.
Exercise:
1. Consider the reference string 9,7,6,1,7,6,1,2,7,2 the number of frames in memory is 3. Find out the
number of page faults and page hit respective to
FIFO page replacement algorithm
Optimal page replacement algorithm
LRU page replacement algorithm
98
9. Display the values
10. Stop the process
‘C’ Code:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}
Output:
ENTER THE NUMBER OF PAGES
20
ENTER THE PAGE NUMBER
12321521625631361243
ENTER THE NUMBER OF FRAMES
3
100