Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Lab Manual For

Operating System
GOVERNMENT ENGINEERING COLLEGE,
GANDHINAGAR

INFORMATION TECHNOLOGY DEPARTMENT

OPERATING SYSTEM AND VIRTUALIZATION(3141601)

Name : ___________________________________________
Branch : ___________________________________________
Enroll. No : ________________________________________
Year : _____________________________________________
GOVERNMENT ENGINEERING COLLEGE,
GANDHINAGAR

CERTIFICATE

To Whom So ever it may concern


This is to certify that Mr./Ms. ____________________________________
__________________ Enrollment No. ______________________ Of B. E.
Semester IV (IT) Batch ____________________________ has satisfactory
completed the course in Operating System and Virtualization (3141601)
with in Government Engineering College, Gandhinagar.

Date Of Submission Staff In-Charge HOD


________________ _____________ _________
INDEX
Sr No Practical Date Sign Remark

1 To study about UNIX/LINUX OperatingSystem.

2 To Study about UNIXCommands.

3 To study about redirection ofIO and piping.

4 Introduction To shellprogramming.

Write a shell script to find thefactorial of given


5
number.
Write a shell script that greets the user by saying
6 Good Morning, Good Afternoon andGood Evening
according to thesystem time.

7 Write a shell script to findword in file.

Write a shell script that acceptsfile name as a


8 command line argument and convert
its contents in to upper- caseletters.
Write a shell script to check givenstring is palindrome
9
or not.

10 Write a shell script to generate Fibonacci series.


Practical : 1 Date :

Aim : Introduction of Operating System.

Computer System Structure :

• Computer system can be divided into four components:


o Hardware
o provides basic computing resources CPU,
o memory,
o I/O devices.
• Operating system Controls and coordinates use of hardware among various applications and users.
Application programs – define the ways in which the system resources are used to solve the
computing problems of the users Word processors, compilers, web browsers, database
systems, video games.

• Users - People, machines, other computers.

(Computer System Architecture)

Operating System :
• An operating system (OS) is a program that acts as an interface between a user and a
computer. The OS manages computer hardware and system resources, such as memory and
hard disk. It also manages the interaction between users and the computer by accepting
input from the user, Interpreting the input and generating output. The OS forms the base on
which any application software is developed. Some of the popular operating systems are:
o Linux
o UNIX
o Microsoft DOS
o Microsoft Windows 95/98
o Microsoft Windows NT Server 4.0
Functions of an Operating System
• The basic functions that an Operating System are:
o Command Interpretation
o CPU and Process Management
o Memory Management
o I/O Management

o Information and Storage Management


• Along with the before mentioned functions, the operating system should also be able to
provide the following basic services to the users:
o User Interface
o Program Execution
o Security
o Device Management
Resource Allocation and Accounting :
Command Interpretation :
• The central processing unit (CPU) interprets commands entered by a user to perform tasks,
such as copying or deleting files. The CPU can interpret only binary code, which comprises code
containing zeroes and ones. The operating system translates the command to binary code so
that the CPU can interpret the command.
Process Management :
• A process is defined as a program in execution. To run, a program needs to be in the main
memory called RAM. When you run program, the, operating system loads the program in the
memory and the CPU execute instruction at a time. In a multiprogramming environment,
many processes run on the computer at the same time.
Memory Management :
• The, operating system allocates the available memory to the processes. However, it is not
possibleto load all the processes at a given time because the main memory is limited. The main
memory stores processes that are currently running, and the hard disk stores the processes
that are not being executed. The hard disk is used as a temporary storage
Input/output (I/O) Operations and Peripheral Management :
• When you execute an application, it accepts input and produces Output. Applications perform
these I/O operations directly. Therefore, the operating system enables the I/O devices such that
keyboard, the mouse or the printer.
File Management :
• The operating enables you to perform file operations, such as creating, naming, opening,
reading, and closing a file.
Operating System Types:
• There are many types of operating systems. The most common is the Microsoft suite of operating
systems. They include from most recent to the oldest:
Windows XP Professional Edition :

• A version used by many businesses on workstations. It has the ability to become a member of a
corporate domain.
Windows XP Home Edition :

• A lower cost version of Windows XP which is for home use only and should not be used at a
business.
Windows 2000 :

• A better version of the Windows NT operating system which works well both at home and as a
workstation at a business. It includes technologies which allow hardware to be automatically
detected and other enhancements over Windows NT.
Windows ME :
• An upgraded version from windows 98 but it has been historically plagued with programming
errors which may be frustrating for home users.
Windows 98 :
• This was produced in two main versions. The first Windows 98 version was plagued with
programming errors but the Windows 98 Second Edition which came out later was much
better with many errors resolved.
Windows NT :
• A version of Windows made specifically for businesses offering better control over workstation
capabilities to help network administrators.
Windows 95 :
• The first version of Windows after the older Windows 3.x versions offering a better interface
and better library functions for programs.
Unix :
• A system that has been around for many years and it is very stable. It is primary used to be
a server rather than a workstation and should not be used by anyone who does not
understand the system. It can be difficult to learn. UNIX must normally run and a computer
made by the same company that produces the software.
Linux :
• Linux is similar to UNIX in operation but it is free. It also should not be used by anyone who
does not understand the system and can be difficult to learn.
Apple Macintosh :

• Most recent versions are based on UNIX but it has a good graphical interface so it is both stable
(does not crash often or have as many software problems as other systems may have) and easy
to learn. One drawback to this system is that it can only be run on Apple program.

Types of Systems :
Single-user system :
• Single user system used by one person at a time for example: PC (personal computer) The PC is a
popular single-user system. It is a small general-purpose computer that can run programs to
perform a wide variety of tasks.
Single-user, single task :

• As the name implies, this operating system is designed to manage the computer so that one
user can effectively do one thing at a time. The Palm OS for Palm handheld computers is a
good example of a modern single-user, single-task operating system.
Single-user Operating Systems :

• Single-user, single task - As the name implies, this operating system is designed to manage the
computer so that one user can effectively do one thing at a time. The Palm OS for Palm hand
held computers is a good example of a modern single-user, single-task operating system. MS
DOS (disk operating system) is an example of a single-user operating system. MS DOS has a
command-line interface (CLI).
Multi-user Systems :
• On a multi-user system, more than one user can work simultaneously. Multi user systems can
run multiple processes concurrently and share hardware resources, such as printers and disks.
A multi-user operating system :
• This operating system allows many different users to take advantage of the computer's
resources simultaneously. The operating system must make sure that the requirements of the
various users are balanced, and that each of the programs they are using has sufficient and
separate resources so that a problem with one user doesn't affect the entire community of
users.
• Example: Linux, UNIX, Windows NT
Basic Concepts of a Multiuser System :
• The CPU of a multi user system is more powerful than that of a single user system. It can support
multiprogramming and multitasking, two features essential for multi-user systems.
• Example of multitasking: having cup of coffee, reading book, and talking to a friend over
phone You divide your time into smaller units and in each unit of time, you do only one of
the tasks. Similarly, the CPU divides the time between all the active tasks.

• A multi user system consists of a computer with several terminals attached. This enables
varioususers to work on this computer. The terminals can be of two types, smart or dumb, a
dumb terminalconsists of a monitor and a keyboard. It has no hard disk or CPU. In case
of a dumb terminal, themulti user system processes all the requirements. The dumb
terminal only acts as an interfacebetween a user and the multi user system. A smart
terminal has its own CPU and peripherals and can Work independent of the multi user
system. A smart terminal can work on any operating system thatit loaded on to its hard
disk. A smart terminal can also connect to the central unit, when required.

• Example of multi user system: Linux, UNIX, Windows NT.


Real-Time Operating System (RTOS) :
• Real-time operating systems are used to control machinery, scientific instruments and industrial
systems. An RTOS typically has very little user-interface capability, and no end-user utilities,
since the system will be a "sealed box" when delivered for use. A very important part of an
RTOS is managing the resources of the computer so that a particular operation executes in
precisely the same amount of time, every time it occurs. In a complex machine, having a part
move more quickly just because system resources are available.
Introduction to UNIX:

• UNIX is a powerful computer operating system originally developed at AT&T Bell Laboratories.
It is very popular among the scientific, engineering, and academic communities due to its
multi-user and multi-tasking environment, flexibility and portability, electronic mail and
networking capabilities, and the numerous programming, text processing and scientific utilities
available. It has also gained widespread acceptance in government and business. Over the
years, two major forms (with several vendors’ variants of each) of UNIX have evolved: AT&T
UNIX System V and the University of California at Berkeley’sBerkeley Software Distribution
(BSD). This document will be based on the Sun OS 4.1.3_U1, Sun’scombination of BSD UNIX
(BSD versions 4.2 and 4.3) and System V because it is the primary version ofUNIX available at
Rice. Also available are Solaris, a System V based version, and IRIX, used by SiliconGraphics
machines.

(Unix Version)

Different “Flavors” of UNIX :


• IBM’s AIX and HP’s HP-UX are heavily used in business.
• Oracle’s (formerly Sun’s) Solaris once powered 70% of the web / e-mail servers on the Internet.
• Apple’s MacOS X is a user-friendly desktop.
• Linux is very high performance and free, which makes it ideal for HPC clusters.

Accessing a UNIX System:


There are many ways that you can access a UNIX system.
Console :
• Every UNIX system has a main console that is connected directly to the machine. The console is a
special type of terminal that is recognized when the system is started. Some UNIX system
operations must be performed at the console. Typically, the console is only accessible by the
system operators, and administrators.
Dumb terminals :
• Some terminals are referred to as "dumb" terminals because they have only the minimum
amount of power required to send characters as input to the UNIX system, and receive
charactersas output from the UNIX system. Personal computers are often used to emulate
dumb terminals,so that they can be connected to a UNIX system. Dumb terminals can be
connected directly to a UNIX machine, or may be connected remotely, through a modem, a
terminal server, or other network connection.
Smart terminals :

• Smart terminals, like the X terminal, can interact with the UNIX system at a higher level. Smart
terminals have enough on-board memory and processing power to support graphical interfaces.
The interaction between a smart terminal and a UNIX system can go beyond simple characters to
include icons, windows, menus, and mouse actions.
UNIX Architecture :

The Linux Operating System :


The History of Linux :
• In 1969, Ken Thorn son and Dennis Ritchie developed a small, general-purpose operating system
called UNIX. Traditionally, all operating systems were written in the assembly language and so
was UNIX. In 1973, Thompson and Ritchie rewrote the UNIX operating system in C.
• In 1974, UNIX was licensed to universities for educational purposes and made commercially
available later. Many vendors, such as Sun, IBM, and Hewlett-Packard, purchased the source
code of UNIX and developed version of UNIX. Most of these versions were proprietary and
maintained by their respective hardware vendors.
• The source code of these versions was not freely available, so the developers had to wait for a
long time for the release of bug fixes.
• In 1984, Richard Stallman's Free Software Foundation (FSF) began the GNU (GNU's Not UNIX) project to
create a free version of the UNIX operating system. The FSF built a number of tools that could be freely
used, read, modified, and redistributed.
• By 1990, the FSF developed a number of tools but the kernel was still not created.
• In 1991, Linus Torvalds developed a kernel and called it Linux.
• In 1992, the Linux kernel was combined with the incomplete GNU system to form a completely free
operating system. The operating system is called GNU-l Linux because it is a combination of GNU and
Linux.
Some of the distributors of Linux are :

Distributer Name Website


Red Hat http://www.redhat.com
Caldera http://www.caldera.com
Mandrake http://www.linux-mandrake.com
Debian http://www.debian.com
SuSE http://www.suse.com
Slackware http://www.slackware.com

Linux Architecture :
• The GNU/Linux operating system consists of a kernel, a shell, utilities, and application
programs.

• The architecture of the Linux operating system is displayed below :

(Component Of Linux OS)

Kernel :
• Kernel is the heart of the operating system. The core of the Linux system is the kernel, which
is also the operating system program. The kernel controls the resources of a computer,
allocating them to different users and tasks. It interacts directly with the hardware, making
programs easy to write and portable across different hardware platforms. However, the user
does not interact directly with a kernel. Instead, the logon process initiates a separate,
interactive program called the shell for each It is the low level core of the System that is the
interface between applications and H/W.
Shell :

• Linux.-has a simple user interface called the shell. The shell provides services for a user. A user
interacts with the computer by using the shell. The user need not know about the intricate
details of the hardware. Some of the common shells in Linux are bash, sh, tcsh, csh, and
ksh. The shell is a program that sits on the as an interface between users and kernel it is a
command interpreter and also has programming capability of its own.

• Shell Types:
o Bourne Shell (sh) (First shell by Stephen Bourne)
o C Shell (csh)
o Korn Shell (ksh)
o Bourne Again Shell (bash)
• Linux Utilities and Application Programs:

• Linux utilities or commands are a collection of programs that service 'processing


requirements. These programs can be started by using the shell. In addition to the utilities
that are a part of the Linux operating system, many Linux-based application programs,
• such as database management systems and word processors, are available from independent
software vendors.
Features and Utilities in Linux
Multiprogramming:

• Linux allows several programs to be executed simultaneously by different users. This feature
is called multiprogramming.

Time-Sharing :
• Multiprogramming is possible on the Linux system due to the concept of time-sharing. In time-
sharing, the operating system has to manage various programs simultaneously. Programs are
queued, and CPU time is shared among programs. Each program receives CPU time for, a
specific period and is then replaced in the queue.
Multitasking :
• A program in Linux is broke down into tasks, such as reading from or writing to the disk or
waiting for input from user. The ability of any OS to handle the execution of multiple tasks is
known as multitasking when a task is waiting for the completion of another task, the CPU,
instead of wasting time, starts executing the next task. Therefore, while one task is waiting
for input from the user, another task could be reading from the hard disk. The kernel is
responsible for scheduling the tasks.
Virtual Memory :

• The amount of physical memory might not always be sufficient to execute large applications
or enable multiple applications to be active at a given time. In such situations, a partition that
is a logical portion of the hard disk can be utilized as artificial or virtual memory. The operating
system places the programs and data, which are not frequently used, in this portion of the hard
disk and loads them in the memory, whenever required. Therefore, the operating system
uses the resources of the computer optimally.
Samba :
• The name Samba is derived from the Server Message Black protocol or SMB. SMB is the
protocolused by Microsoft operating systems to share files and printers. Samba is a suite of
programs thatimplement the 5MB protocol on Linux. Using Samba, you can share a Linux
file system with Windows 95 Windows 98 or Windows NT. You can also share a Windows
95, Windows 98, or Windows NT filesystem with Linux. Similarly, you can use 5MB to share
printers connected to Windows 95, Windows 98, or Windows NT computers with Linux.

Linux File System :

• Single hard disk can store data in the form of thousands of files. An operating system provides
file system to organize these files. A file system is a mechanism used by a system to store
and manage files and directories on a storage medium.
• UNIX file system was a feature that was not available in other operating systems. The file
systemhas a hierarchical structure that enables you to store files in directories. Directories are
similar to the drawers of a filing cabinet. Just as a drawer contains files, each contain similar
documents, directories can be created on a disk to store files that contain similar data. In a
filing cabinet, a user specifies names for the drawer labels and contents. Similarly in a UNIX
file system, a user can decide a directory name and the files to be in the directory. The
hierarchy in the Linux file system is similar to that of the UNIX file system.

• The administrator of the Linux operating system can store the home directories for all the
users in the /home directory.
• For example, the tom directory is the home directory for the user tom. Tom can store all files in
his home directory tom or create directories in the home directory. The directory tom contains
two files program1 and program2, and two directories Desktop and Templates. The Desktop
directory contains two files, Default and start. All the files are stored on the disk in a main
directory which is called the root Directory. The root directory is subdivided into other
directories: bin, boot, home, usr, etc, and dev.

(Linux File System)

• The /bin directory stores many utilities available in Linux. These utilities are the commands in
the Linux operating system. The directory that stores the utilities available in Linux is named
bin because the utilities are stored in the binary format.
• The /dev directory stores all the device-related files for the Linux operating system.
• The /etc directory stores the data related to the operating system, including the essential
operating system programs and configuration files. Occasionally, users and the operating
system might need to refer to configuration files, such as the passwd file.
• The /lib directory contains data libraries for the compilers, such as the C language routines,
installed in the Linux operating system.
• The /home directory contains the home directories of all the users.
• The /usr directory stores the operating system files that are not required during the
startup process. The /usr directory also contains the bin directory, which stores many utilities.
The
/usr/bin directory is different from the /bin directory.
• The /var directory contains information specific to different utilities available in Linux: for
example, the /var/log directory contains log files relative to the operating system.
• In a file system hierarchy, a file is referred to by its path, which consists of the file name
preceded by the name of the directory containing e/e. The path can contain a set of directories,
in which one directory contains another directory and so on until you access the '/ (root)
directory. The file name and different directory names in the path are separated by the '/'
symbol.
• For example the complete path of the file .profile is /home/mthomas/.profile

• Similarly, the path for the file 1s is /bin/1s. Notice that the '/' symbol is a special character
and cannot be included in a file or directory name In a hierarchical inverted tree-like structure,
the operating system provides faster access to files because groups of files are isolated from
each other. To locate a file, the operating system needs to search only one directory.
Alternatively, if there are no subdirectories and all the files are stored in the root directory;
the operating system needs to search the entire list of files to locate a specific file.
Types of Files in Linux :
• Linux, information is stored in files. Therefore, in addition to a user's program and data files
there are special files that contain information about directory contents or various
input/output devices connected to the Linux operating system.

• In Linux, a device is also a file. All the information sent to the visual display unit (VDU) is
treated asif it were sent to a file.
• In Linux there are three types of files:
o Ordinary
o Directory
o Special
Ordinary Files :
• Created by a user are ordinary files. Ordinary files include all data, program, object, files. A user can
modify ordinary files.
Directory Files :

• When you create a directory in Linux, a directory file is automatically created by the operating
system. The directory file has the same name as the directory and contains information about the
files stored in the directory. For example, the directory! home/Steve contains a directory file called
Steve in the directory /home. This directory file contains information about all the files and
directories in the directory Steve. A user cannot modify a directory file. However, when a file or sub
directory is added to the home directory, the directory file is modified automatically by the Linux
operating system.
Special Files :
• Most of the system files in Linux are special flies. Special files are usually associated with
input/output devices. Special files are Stored in standard Linux directories, such as /dev and /etc. A
user cannot modify its special files.
Linux supports the following types of special files :
Character Device Files :

• Character device files can read and write data, one character at a time. A modem is an
example ofa character device file. Character devices are also known as sequentially accessed
devices.
Block Device Files :

• Block device files can access one block of data at a time. A block of data comprises either - 512
or1,024 bytes. The kernel reads or writes a minimum of one block of data at a time. The
kernel collects datain the memory and then makes the data available to a user. Block
devices allow random access, whichmakes input/output operations faster. An example of a
block device is a hard disk. Many devices can actas either character or block devices,
depending on the command used to access the device.
Hard link :
• Single files that have multiple names specify the hard link only for a file and not for a
directory.

• It’s known as hard links because they create a direct link to an in node.
Symbolic Files :
• Symbolic links are similar to hard links, but you can specify symbolic links for files
across differentfile name.
Types of Users in Linux
A System Administrator (SA) :
• A System Administrator is responsible for the smooth operation of the Linux operating
system. The SA starts the system console on which the operating system is installed. The
SA also creates usersand user groups on the Linux operating system. Additionally, the SA
makes backups to prevent data lossif the operating system crashes. In Linux, the SA is also
known as the root user. The SA has all the rightsfor the Linux operating system.
File Owner :
• The user whose creates a file is known as the owner of the file. The owner of a file can
performany operation on that file, such as copying, deleting, or editing.
Group Owner :
• Consider the following situation: A project team of five people from ABC Telecommunications is
working on a software development project for a marketing agency. An analyst leads the
team. The other four members are programmers. The team is working on the Linux
operating system. The data provided by the agency is extremely confidential. Therefore, the
data file needs to be created in the analyst's home directory.

Sign : _______________
Practical : 2 Date :

Aim : To Study about Various UNIX Commands.

1. man :
• This command offers an on-line help facility for any document. Man display the
document oftencalled man documentation – of practically every command on the system.

• Syntax: man [option] documents or command


• Example:
$man wc

After executing this command which will display a user manual for command ws.

2. cal :

• The cal command is used to see the calendar of any specific month or complete year.
• Syntax : cal [ [month] year ]
• Example :
$cal This displays a current month calendar of current year.

December 2011

Sun Mon Tue Wed Thu Fri Sat

01 02 03

04 05 06 07 08 09 10

11 12 13 14 15 16 17

18 19 20 21 22 23 24

25 26 27 28 29 30 31

$cal December 2012

$cal 2012

3. date :
• This command displays a current Date of System. This command proceeded by + symbol and
followed by % operator, and single character describing the format.
• Syntax: date [option]
• Option:
o d : The day of the month(1 to 31).
o y : The last two digit of year.
o h, m, s : Hour, Minute and Second
o d : The date in format ( mm/dd/yyyy ).
o t : The time in format ( hh:mm:ss ).
• Example:
$date

Sun Dec 18 07:35:55 IST 2011

$date +%d
$date +%y

$date +%h

$date +%n

4. echo :
• This command is often used in shell script to display a diagnostic message in the terminal or to
issue prompt for taking user input.
• Syntax : echo [option] [string message]
• Options :
o -n : do not output the trailing newline.
o -e : enable interpretation of escape sequence.
o -E : disable interpretation of escape sequence. String message: display string message on
terminal.
• Example :
$echo Hello GEC Hello GEC

$echo This is GEC '\t' GTU

$echo -e This is GEC '\t' GTU

5. script :
• This command is used to record a session of terminal which will be stored on hard drive or print

• later.
• Syntax : script [option] [-c COMMAND ] [ file ]

• Option:
o -a : Appending output file or typescript.
o -e : Return the exit code of child process.
o -f : Flush output after each write.
o -q : Be quiet.
o -t : Output timing data to standard error.
o -c COMMAND: Run the COMMAND rather than an interactive shell. This makes it easy for a
script to capture the output of a program that behaves differently when its stdout is not a
tty.
• Example :
$script

This record session.

$script filename

6. passwd :
• This command is used to create or change existing password of your system.
• Syntax : passwd [ option] [ login ]
• Option :
o -a : This option can be used only with -S and causes show status for all users.
o -d : Delete a user's password (make it empty). This is a quick way to disable a password
for an account. It will set the named account password less.
o -l : Lock the password of the named account. This option disables a password by
changing it to a value which matches no possible encrypted value (it adds a ´!´ at the
beginning of the password).
o -n : Set the minimum number of days between password changes to MIN_DAYS. A value
of zero for this field indicates that the user may change his/her password at any time.
o -u : Unlock the password of the named account. This option re-enables a password by
changing the password back to its previous value (to the value before using the -l
option).
o -x : Set the maximum number of days a password remains valid. After MAX_DAYS, the
password is required to be changed.

• Example :
$passwd Changing password for karan (Current) UNIX password: Enter new UNIX password:
Retype new UNIX password:

7. who :
• The who command displays an informative listing of users with user-id or user-name.
• Syntax : who [option]
• Options:
o -H : This option prints the header of column.
o -u : This option combine with -h it prints a more details.
• Example:
$who

root pts/0 2011-12-17 09:53 (:0.0)

$who -H

$who -Hu

8. logname :

• This command prints user's login name.


• Syntax : logname
• Example : $logname
9. ttv :

• Since UNIX treats even terminal as file it's reasonable to expect a command that tells you the
filename of terminal you are using.
• Syntax : tty [option]

• Option: -s : Print nothing , only return exit status.


• Example : $tty
10. pwd :
• This command prints a name of current/working directory.
• Syntax : pwd [ option ]
• Option :
o -L : use PWD from environment, even if it contains symlinks
o -P : avoid all symlinks

• Example :
$pwd

/home/xyz

$pwd -L

$pwd -P

11. cd :

• This command is used to move (change) working directory.


• Syntax: cd [filename or directory-name]

• Example :
$cd Desktop After executing this command our working directory is Desktop.

12. mkdir :

• This command is used to create directory. The command is followed by names of the directories
to be created.
• Syntax : mkdir [option] [directory-name]
• Option :
o -m : set file mode.
o -p : no error if existing, make parent directories as needed.
o -v : print a message for each created directory.
• Example :
$mkdir patch A directory patch is created under the current directory.

13. rmdir :
• The rmdir (remove directories) command removes directories.

• Syntax : rmdir [option] directory-name


• Option :
o -p : remove DIRECTORY and its ancestors.
o -v : output a diagnostic for every directory processed

• Example :
$rmdir patch A patch directory is removed under the current directory.

14. cat :
• This is one of the most well-known commands of the UNIX system. It is mainly used to display
the content of a samll file on terminal.

• Syntax : cat [option] [file]


• Option :
o -v : display non-printing character.
o -n : numbering lines

• Example :
$cat test.txt

Hello GEC! Hello world!

$cat -v test.txt

$cat -n test.txt

15. cp :
• The cp(copy) command copies a file or group of files. It creates an exact image of the file on disk
with different name. This command requires at least two file names.

• Syntax : cp [option] source destination


• Option :
o -i : Interactive copy. The -i option warns the user before overwriting the destination file.
o -R : Copying Directory Structures. The -R option behaves recursively to copy an entire
directory structure.

• Example :
$cp test.txt test1.txt

This command makes copy of test.txt to test1.txt.

$cp -i test.txt test1.txt

$cp -r prg prog

16. ln :
• A file is linked with the ln(link) command, which takes two filename as arguments. The
command
• can create both a hard and soft link.
• Syntax : ln [option] Target Link-name
• Option :
o -L : make hard links to symbolic link references
o -P : make hard links directly to symbolic links
o -s : make symbolic links instead of hard links

• Example :
$ln emp.lst employee This command links emp.lst with employee.

17. nl :
• Used for numbering the lines of files.

• Syntax : nl [option] file-name


• Example :
$nl test.txt

1 hello

3 hello

4 world

18. rm :
• The rm command deletes one or more files.
• Syntax : rm [option] filename
• Option :
o -i : prompt before every removal
o -r , -R : remove directories and their content recursively.
• Example :
$rm test.txt This command removes test.xt file.

$rm -i test.txt

$rm -r prg

19. mv :
• The mv command renames (move) files. It has two distinct function.
• It renames a file or directory.

• It moves a group of files to a different directory.


• Syntax : mv [option] source destination
• Option :
o -i : prompt before overwrite.
o -f : do not prompt before overwriting.
• Example :
$mv test.txt d.txt

This command renames test.txt to d.txt

$mv d.txt Downloads/d.txt

This command moves d.txt from current directory to download directory


20. more :

• The man command displays its output page at a time. This is possible because it sends its output
to a pager program.
• Syntax : more [filename]
• Example : $more chap2 // This command views a file chap2.

21. wc :

• This command counting lines, word and characters of file. It takes one or more filenames as
arguments and displays a four-column output.
• Syntax : wc [option] filename(s)

• Option :
o -l : display number of line of given file.
o -w : Display number of word of given file.
o -c : Display number of characters of given file.

• Example :
$wc test.txt

3 2 14 test.txt

$wc -l test.txt

$wc -w test.txt

$wc -c test.txt

22. cmp :
• This command is used to comparing two files. The two files are compared by byte by byte.,and
the location of first mismatch echoed to screen.
• Syntax : cmp [option] File1 File2
• Option :
o -b : Print differing byte.
o -l : Output byte numbers and value of all differing bytes.
• Example :
$cmp test.txt test1.txt

test.txt test1.txt differ : byte 8 ,line 2

$cmp -b test.txt test1.txt

$cmp -l test.txt test1.txt

23. touch :
• This command is used to changing the Time Stamps. You may need to set the modification and
access time to predefined value.
• Syntax : touch [option] [expression] filename(s)

• Option :
o -a : Change only access time.
o -m : Change only modification time.
o -t : use [[CC]YY]MMDDhhmm[.ss] instead of current time
• Example :
$touch test.txt

If the file test.txt is exist then this command update access time and modification time

24. ls :
• This command is used to obtain a list of all filenames in the current directory.
• Syntax : ls [option] filename
• Option :
o -x : Multi-column output
o -F : Marks executable with *, directory with / and Symbolic link with @.
o -a : Show all filename beginning with a dot including . And ..
o -R : Recursive list.
o -r : Sorts filename in reverse order.
o -l : Long listing in ASCII sequence showing seven attribute of file.
o -d dirname : List only dirname if dirname ids directory.
o -t : Sorts filename by last modification time.
o -u : Sor filename by last access time.
o -i : Display inode number.

• Example :
$ls 03161430 ch1.txt~ Desktop examples.desktop Templates workspace 12171010 chirag
Documents Music typescript ch.txt Downloads Pictures Ubuntu One ch1.txt ch.txt~ emp.lst Public

$ls -x

$ls -F

$ls –a

$ls –R

$ls –r

25. umask :
• When you create files and directories, the permission assign to them depend on the system's
default setting.
• rw-rw-rw- (octal 666) for regular files. rwxrwxrwx (octal 777) for derectories.
• However you cannot see these permission when you create a file or directory. This command is
used without parameter.
• Syntax : umask
• Example : $umask 0002

26. chmod :
• This command is used to change permission of file or directories.
• Syntax : chmod [option] Octal-Mode File
• Option :
o -c : Like verbose but report only when change is made.
o -v : Output diagnostic for every file processed.
o -R : Change file and directories recursively.
• Example :
$ls -l test.txt

rw-rw-r-- 1 chirag chirag 14 2011-12-18 18:51 test.txt

$chmod 777 test.txt rwxrwxrwx 1 chirag chirag 14 2011-12-18 18:51 test.txt

27. tee :
• This command is used to read standard input and write to standard output and file.
• Syntax : tee [option] [file]

• Option : -a : Append to given file do not overwrite.


• Example :
$tee -a test.txt

hello hello gec

Now content of test.txt

hello hello gec

28. head :
• The head command, as the name implies, display the top of the file. When used without an
option it display first ten lines of a file.
• Syntax : head [option] filename
• Option :
o -c k : This will display first k byte of file.
o -n k : This will display first k line of file.
• Example :
$head test.txt

hello hello gec


$head -c 10 test.txt

$head -n 2 test.txt

29. tail :

• The tail command, as the name implies, display the bottom of the file. When used without an
option it display last ten line of file.
• Syntax : tail [option] filename

• Option :
o -c k : This will display last k byte of file. If +k is used then it will skip first k byte of file and
display remaining file content.
o -n k : This will display last k line of fle. If +k is used then it will skip first k line of file and
display remaining file content.
o -v : always output headers giving a filename.
• Example :
$tail test.txt hello hello gec

$tail -c 10 test.txt

30. cut :
• The feature of cut and paste command will be illustrated with specific reference to the file
shortlist, which stores the first five line of test.txt
• Syntax : cut option [filename]
• Option :
o -c : Select only these characters.
o -f: Select only these fields.
o -d : It is used for delimeter.
• Example :
$cut -c 3 test.txt | tee shortlist

ItItI

$cut -f 2 test.txt | tee shortlist

$who

$who | cut -d “ “ -f1

31. paste :
• What you cut with cut command can be pasted back with the paste command but vertically
rather- then horizontally.
• Syntax : cut [option][filename]
• Option :
o -d : use delimiter.
o -s : use paste one file at a time.
• Example :
$cut -c 3 test.txt | tee shortlist1

$cut -c 5 test.txt | tee shortlist2

$paste shortlist1 shortlist2

32. sort :
• Sorting is an ordering of data in ascending or descending sequence. The sort command orders a
file.
• Syntax : sort [option] filename

• Option :
o -t char : Use delimeter char to identify fields.
o -k n : Sort on nth field.
o -k m,n : Start sort on mth field and end sort on nth filed.
o -u : Remove repeated lines.
o -n : Sorts numerically.
o -r : Reverse sort order.
o -f : Folds lowercase to equivalent uppercase(case sensitive sort).
o -m list : Merge sorted file in list.
o -c : checks if file is sorted.
o -o flname : Places output in file flname.

• Example :
$sort test.txt

hello gec world

$sort -r test.txt

$sort num.txt

$sort -n num.txt

33. uniq :
• This command is used to locate repeated and non-repeated lines. When you concatenate or
merge files, you'll face problem of duplicate entries creeping in. This command requires a sorted
file.

• Syntax : uniq [option] [input [output]]


• Option :
o -c : Prefix line by number of occurrences.
o -d : Only print duplicate lines.
o -u : Only print unique lines.
• Example :
$sort test.txt | uniq

hello gec world

$sort test.txt | uniq -d

$sort test.txt | uniq -c

$sort ch.txt | uniq -u

34. tr :
• This command translates characters. So far, the commands have been handling either entire line
or column. The tr(translate) filter manipulates individual characters in a line. Note that tr takes
input only from standard input; it does not take filename as arguments.
• Syntax : tr [option] exression1 exression2 standard input
• Option :
o -d : Delete a characters.
o -s : Compressing multiple consecutive characters.
o -c : Complementing value of expression.
• Example :
$tr '|' '-'

gec |

gec -

$tr -d '|'

$tr -s ' '

$tr -c '[:print:]' '?' < test.txt

$tr -c '[a-z][A-Z]' '?' < test.txt

$tr -c '[:cntrl:]' '?' < test.txt

35. grep :
• This command is used to search pattern. grep scan its input for a pattern and displays lines
containing a pattern, the line number or filenames where the pattern occurs.
• Syntax : grep [option] pattern filename(s)
• Option :
o -E : Interpret pattern as extended regular expression.
o -G : Interpret pattern as basic regular expression.
o -P : Interpret pattern as per regular expression.
o -i : Ignore a case.
o -n : The n option display the line numbers containing the pattern, along with line.
o -v : select all lines except those containing the pattern.
o -c : Counting lines containing pattern.
o -l : Display filename containing pattern.
o -e : Matching a multiple pattern.
o -f : Taking pattern form as file.
• Example :
$grep “gec” test.txt hello gec world

$grep gec test.txt test1.txt

$grep -i gec test.txt

36. expr :
• This command is used for computation and string handling. This command combines two
functions in one.
o Perform arithmetic operation on integer.
o Manipulate strings.
o Determining length of string.
o Extract a substring.
o Locate the position of a character in a string.
• Syntax: expr expression
• Example :
$expr 3 + 5

$expr 5 – 2

$expr 5 \* 2

$expr 5 / 2

$x=4 y=4

$expr $x \* $y

$x=6 y=2 ; z=`expr $x + $y`

$echo $z

Length of String :

• for finding length of string the regular expression.* signifies ot expr that has print the number of
characters.
$expr “abcdefg” :'.*' 7

Extracting a substring :
• expr can extract a string enclosed by the escaped characters \(and \).The below example
extracting last 2-digit of year from 4-digit.
$str=2012

$expr “$str” : '..\(..\)' 12


Locating position of character :

• expr can also return the location of the first occurrence of character inside a string. We use
[^alpha]*alpha to locate a perticular character.
$str=abcdefg ; expr “$str” : '[^d]*d'

Sign : _______________
Practical : 3 Date :

Aim : To study about redirection of IO and piping.

I/O Redirection :

• We have discussed essential UNIX commands. Now we look at something different: Input/output
Redirection.

• In all operating systems, there is a standard input device and a standard output device. In UNIX, as
also in most other operating systems, the standard input device is the keyboard and the standard
output is the display screen.

• Thus if a command is described as reading from the standard input and writing to the standard
output, that means it takes input from your keyboard and sends output or error messages to your
screen.

• Special files that instruct all the programs to accept standard input from the keyboard and direct
the standard output to the display, are provided by UNIX. The three streams, i.e. the standard
input, standard output and standard error are denoted by the numbers 0, 1 and 2 respectively.

Stream Device Value

Standard Input Keyboard 0

Standard Output Terminal Screen 1

Standard Error Terminal Screen 2

• Why not just use the terms keyboard and screen for the standard input, output, and error? Because
UNIX allows you to change the standard input and output temporarily by using what is known as
redirection and piping.

• Sometimes it is useful to redirect the input or output to a file or a printer. For example you might
want to redirect a directory listing from the screen to a file. Unix provides redirection symbols for
the purpose.
Redirection Operator Resulting Operation

command > file stdout written to file, overwriting if file exists

command >> file stdout written to file, appending if file exists

command < file input read from file

command 2> file stderr written to file, overwriting if file exsits

command 2>> file stderr written to file, appending if file exists

cmd1 | cmd2 Make standard output of cmd1 the standard input of cmd2.

Redirecting input with the < sign :

• To redirect input, specify a filename after a less than sign (``<'') on a command line:

command < file

$ cat < myfile


• would take input from the file designated as myfile rather than from standard input. An example of
redirection of output into a file:

$ cat food # reads from file "food"


$ cat # reads from stdin (from your keyboard)

$ head food # reads from file "food"


$ head # reads from stdin (from your keyboard)

$ sort food # reads from file "food"


$ sort # reads from stdin (from your keyboard)
$ sort <food # reads from stdin (now from the file "food")

• When is this mechanism useful? A typical example is when you want to send someone--via the mail
command--a message or file you've already created. By default, the mail command expects input
from standard input (that is, the keyboard). But suppose you have already entered the information
to be sent (to a user with the login name jim) in a file called report. Rather than retype that
information, you can simply redirect input to mail as follows:
mail jim < report

Redirecting output with the > sign:


• To redirect output (from standard output) to a file, specify a filename after the greater than sign
(``>'') on a command line:
command > file

$ date > outfile.txt

$ cat file 1 > file2

$ echo "Hello World!" > my_files [Enter]

$ cat my_files [Enter] Hello World!

$ date >> outfile # output is *appended* to outfile; no truncation

An example of redirection of output into a file:

$ echo Hello # O/P goes to Terminal Hello

$ echo Hello > file # Erase file contents; send O/P to file

$ cat file # Display File Contents. Hello

$ echo There >> file # Append O/P to end of the file

$ cat file # Display File Contents. Hello There

Caution :

• If you redirect output to a file that already exists, the output of your command will overwrite the
contents of the existing file.
• Let us put these operators to a practical stint. Consider this command:
• On executing this you will promptly be returned to the $ prompt. The redirection operator declares
file2 to be the standard output ousting the terminal screen from that role. Thus the output of cat
which is normally sent to the screen is now sent to file2 and not to the screen. If the file file2 does
not exist, it is created. If it does exist, it is wiped clear and refilled with the new data. Thus, the
output going to the Screen has been redirected to a file.
• Note that this change in standard output is temporary. When the command ends, your terminal
once again becomes the standard output. Now let's look at input redirection. The Unix manual says
that cat reads from the standard input if no input file is given. This allows us to do the following:
$ cat
• Did you hear the story about the optimist and the pessimist? The optimist goes to the window
every morning and says, "Good morning, God". The pessimist goes to the window and says, "Good
God, morning".
Ctrl d

• Did you hear the story about the optimist and the pessimist? The optimist goes to the window
every morning and says, "Good morning, God". The pessimist goes to the window and says, "Good
God, morning".
• Any command that accepts standard input also input redirection. So let’s try that out with cat.
$cat < newfile
• One of the best things about getting older is that all those things you wanted and couldn't afford
when you were younger, you no longer want.
• Here the file newtile became the standard input, and cat read its contents and displayed them on
the screen. The same thing could as well have been achieved by saying.
$ cat newfile

• One of the best things about getting older is that all those things you wanted and couldn't afford
when you were younger, you no longer want.
• Though both the commands produce the same output there is a subtle difference between the
two. In the latter example newfile was not the standard input. Instead, the standard input
remained the terminal, and the internal programming of cat caused the newfile file to be opened in
addition to the standard input.
• Indeed, cat, like many file-reading programs, can read the standard input and a file input during the
execution of the command. The standard method (and the one used by cat) is to use a hyphen
instead of a filename to stand for standard input. Here is an example that uses the file newfile as
the first input and the standard input (here the keyboard) as a second input:
$ cat newfile :

• We all shall plant some trees we will never sit under.


Ctrl d

• One of the best things about getting older is that all those things you wanted and couldn't afford
when you were younger, you no longer want.
• We all shall plant some trees we will never sit under.
• As you can see, cat concatenated the two inputs. Since the filename came first, it was printed first.
• Then the keyboard input, represented by the hyphen, was printed.
• Sometimes we may use both the redirection operators at once as shown below.
$ cat < currentfile > newfile

• The first part of redirection, < currentfile, indicates that input is to be taken from the file
currentfile, and the second part of redirection, > newfile establishes that output is to be routed to
the file newfile. The order in which the two indirection operators are used doesn't matter. We
could have obtained exactly the same effect even by saying,
$ cat > newfile < currentfile
• Another redirection operator which is popularly used is the append operator, ». It is similar to >,
except if the target file already exists, the new output is appended to its end. For example,
$ who » logfile

• This command appends the current list of users who have logged in to the end of the file logfile.
• Write down output of following commands.
$ ls > filelist

$ cat test.txt test1.txt>> report

$ cat test.txt > test1.txt

$ cat < test.txt > test1.tx

$ cat > file < file1

$ date ; who

$ date ; who > logfile

$ (date ; who) > logfile

Piping :
• The philosophy of UNIX commands is that each does a small job but does it quite comprehensively.
Quite often a single Unix- command does not suffice to solve a problem or do a task. That's the
time we can try joining commands together. The chief tools for this are redirection and the pipe. If
you have migrated to Unix from some other operating systems you probably know about these
facilities. However, their true power is tapped best (arguably) by the UNIX commands.
• Redirection facility of UNIX lets us connect commands to files. The UNIX piping facility lets us
connect commands to other commands. -This facility is of utmost importance in combining UNIX
commands and operations. It can be really useful to redirect the output of one program so that it
becomes the input of another program, thereby joining the two programs. To send the output of
one command as input for another, the two commands must be joined using a pipe ( | ) character.
• It is possible to join command using a pipe since many UNIX command accept input from the
standard input and send output to the standard output. Incidentally, such command is known as
filters.
• Thus filter is a program which can receive a flow of data from standard input, process (or filter) it,
and send the result to the standard output.

Filter Purpose

cat Concatenates and display files

more Display a file one screenful at a time

head Prints the first few lines of file

tail Display the last few lines of file

grep Searches a file for a pattern

tr Translate character in file

cut Cuts out selected fields of each line of file

paste Merges lines of file

wc Count the line, word and character


• Let us now see a few examples of piping.
$ls | wc

• Here the output of ls becomes the input to we which promptly counts the number of lines it
receives as input and displays this count on the screen. Instead of displaying this count, what if
want to store the count value in a file? Simple, use the output redirection as shown below:
$ ls | wc > countfile

• This example shows that piping and redirection can go together. Let's consider another example
$ who | sort

• Here, instead of displaying the output of who command on screen it is pipe to sort. Sort sorts
whatever it receives from the output of who command it will display a sort list on screen. Once
again, if we want we can redirect this sorted output to the file by saying.
$ who | sort > file-name

• In many cases, input from a pipe can be combined with input from files. The trick, as in combining
redirection with files, is to use the special symbol - (a hyphen) for those commands that recognize
the hyphen as standard input. For instance consider this command:
$ who | sort - logfile > newfile

• The output from who becomes the standard input to sort. Meanwhile, sort opens the file logfile.
The contents of this file are sorted together with the output of who (represented by the hyphen),
and the sorted output is redirected to the file newfile.
$ who | tee logfile | sort

• Here, the output of who becomes the standard input of tee. tee now sends one copy of the input to
sort through one pipeline, whereas the other copy is stored in a file called logfile.
• What if we want to store the output of who in two files and still manage to send one copy to sort.
• Simple just mention the two filenames after the tee command as shown below:
$ who | tee test.txt test1.txt | sort

• If you wish to append the output of tee to a file, just use its -a option as shown below:
$ cat file1 file2 | tee -a completefile | more

• In this pipeline the output of cat (contents of the files file1 and file2) are appended to the existing
contents of the file completefile. Another copy of output of cat is sent to more for displaying on the
screen.
• So far we have redirected only the standard input and the standard output. We can however also
redirect the standard error. The following example shows this can be done.
$ cat test.txt > ch.txt 2 > error.txt

• If the file test.txt exists, then the contents of that file would be copied into ch.txt. However, if it
does not exist, then an error message would be produced. However instead of displaying the error
message on the screen it would be redirected lo a file error.txt. Note that the > symbol redirects
the standard output whereas 2> redirects the standard error. While redirecting the standard
output instead of > we may as well use 1>.
• Assuming that the file test.txt did not exist let's check out the contents of error.txt.
$cat error.txt

cat: test.txt : No such a file or directory.

• This is the error message produced by the cat command when it failed to locate the file test.txt.
• Obviously, had test.txt existed its contents would have been copied into the file ch.txt.
Exercises: Construct pipeline to execute following jobs:
1. Output of who should be displayed on the screen with value of total number of users who have
logged in displayed at bottom of list.

2. Output of ls should be displayed on the screen and from this output the lines containing the word
'spce' should be counted and the count should be stored in a file called SPCE.txt

3. Content of file1 and file2 should be displayed on the screen and this output should be appended to
file3.

4. From output of ls the lines containing 'spce' should be displayed on the screen along with the
count.
5. Name of cities should be accepted from the keyboard. This list of cities should be combined with
the list of cities present in the file CityFile. This combined list should be sorted and sorted output
should be stored in a file called NewCityFile.

6. All files present in a directory dir1 should be deleted. Any error, if occurs while carrying out this
operation should be stored in file called ErrorFile.

Sign : _______________
Practical : 4 Date :

Aim : Introduction to shell programming.

Introduction :

• A shell program is nothing but a series of such commands. Instead of specifying one job at a time,
we give the shell a to-do list - a program - that carries out an entire procedure. Such programs are
known as 'shell scripts'. The UNIX shell is an interface between the user and the operating system
itself, and forms one of the major components of the UNIX operating system.

• The Shell also incorporates a powerful programming language that enables the user to exploit the
full power and versatility of UNIX. The programming language incorporates most of the features
that most modern day programming languages offer. For example, it has local and global variables,
control instructions, functions, etc. The shell itself interprets the commands in the shell program
and executes them.

• UNIX uses shells to accept commands given by the user, there are quite a few different shells
available. The most commonly used shells are SH(Bourne Shell) CSH(C Shell) and KSH(Korn Shell),
most of the other shells you encounter will be variants of these shells and will share the same
syntax, KSH is based on SH and so is BASH(Bourne again shell). TCSH (Extended C Shell) is based on
CSH.

• All the shells support processes (both foreground and background), pipes, filters, directories, and
other similar standard features of UNIX. Shell programming is so powerful that several tasks like
system shut-down, checking how much disk space is available etc. are carried out by UNIX using
nothing but the shell scripts.

• The commands dfspace and shutdown are nothing but shell scripts. Each shell has merits and
demerits of its own. Moreover the shell scripts written for one shell may not work with the other
shell. This is because different shells use different mechanisms to execute the commands in the
shell script. Also, the keywords available in one shell to implement the control instructions would
not be available in the other shell.

• Shell programs can be used for a variety of tasks some of which are mentioned below:

o Customizing your work environment. For example, every time you log in if you want to see
the current date, a welcome message and the list of users who have logged in you can
write a shell script for the same.

o Automating your daily tasks. For example, you may want to back up all your programs at
the end of the day. This can be done using a shell script.

o Automating re repetitive tasks. For example, the repetitive task of compiling a C program,
linking it with some libraries and executing the executable code can be assigned to a shell
script. Another Executing important system procedures like shutting down the system,
formatting a disk, creating file system on It, mounting the file system, letting the users use
the floppy and finally unmounting the disk.

o Performing same operation on many files. For example, you may want to replace a string
printf w i t h a String myprintf in all the C programs present in a directory. You should not
use shell programming when the task:

o is too complex, such as writing an entire billing system.

o requires a high degree of efficiency.

o Requires a variety of software tool.


How to write Shell scripts...

• For Example:
#ss1

#usage :SS1 ls who

pwd

• # is the symbol which marks the beginning of the comments SS1 is the name of the file in which we
type shell scripts.

• This shell scripts gives the list of all files in the current directory, list of all user who logged in and
print the working directory.

• To execute shell scripts type SS! At the shell prompt and hit the Enter key:
$SS1 (Enter)

SS1: Execute permission denied.

• Let that not put you off. The 'execute permission denied' from the shell is no bad omen at the very
outset of our programming trip. The reason is, by default every file is to get created with the
permissions 666, i.e. rw-rw-rw- These permissions, as we know, are further modified by a umask.
To know your current umask enter umask at the shell prompt.
$umask 0022

• This is an octal number which signifies what permissions are 'masked' from the file. Our file SS1 got
created with the permissions 666 - 022 which equal 644. Thus, we as owners have the permission
to read and write to the file, but not to execute it. The remedy to this is the chmod command.
$chmod 744 SS1

• This command changes the mode or the permissions available with a file. The new permissions
for SS1 are therefore 744, or rwxr—r--. Again execute SS1 and you would get the expected results.
$ SS1

a.out

ascii.c

calender.

c dance.c
file1

matter

newcal

ss1

tree

aa11 tty01 Nov

06 08:34 aa12 tty3a Nov

06 09:41 karan tty3b

Nov 06 : 10 : 06 aa10 tty3c

Nov 06 : 09 : 12

/usr/karan

Interactive Shell Scripts:

• A program needs to talk to the user, and in turn requires a language. Two very basic words in the
shell vocabulary are read, to accept input, and echo, to display output. The script SS2 given below
illustrates how this work.

#SS2

# Usage: SS2

# An interactive shell script echo What is your name\? read name

echo Hello $name. Happy programming.

Shell Variables :

• Shell variables are an integral part of shell programming. They provide the ability to store and
manipulate information within a shell program.

o The rules for shell variables are as follows:

o A variable name is any combination of alphabets, digits and an underscore (‘ _‘).

o No commas or blanks are allowed within a variable name.

o The first character of a variable name must either be an alphabet or an underscore.

o Variables names should be of any reasonable length.

o Variable names are case sensitive. That is, Name, NAME, name, Name are all different
Variables.

• For example:
Si_int

m_hra

pop_e_8 9

• There is no limit on the length of a variable name; an enormous number of variable names can be
constructed using the aforementioned rules.
Shell Keywords :

• The keywords cannot be used as variable names because if we do so we are trying to assign a new
meaning to the keyword, which is not allowed by the shell. Some implementations of the shell
allow you to construct variable names which exactly resemble the keyword The keywords are also
called 'Reserved words'.

• Following is the list of keywords available in Bourne shell, given here for your ready.
Echo if Until Trap

Read Else Case Wait

Set Fi Esca Eval

Unset While Break Exec

Readonly Do Continue Ulimit

Shift Done Exit Umask

Export for return

Types of variable in UNIX :

• Unix-defined variables or System variables:

• These are standard variables which are always accessible. The shell provides the values for these
variables.

• These variables are usually used by the system itself and govern the environment we work under. If
we so desire we can change the values of these variables as per our preferences and customize the
system environment.

• Unix-defined or System Variables


$ PS1="\A1'hat

next" What next /

• The UNIX as has defined these variables for its own use. The $ prompt that we see is the default
value o f the Unix-defined variable PS1 standing for system prompt 1. We may assign a different
value to PS1 if we want the prompt to be something else other than the $.

• So now every time the system prompts you, it displays not the $ but what next.

• Some of the commonly used system variables and their meaning are given below :
Variable Meaning

PS2 The system prompt Pt2,default value is “>”

PATH Define the path which the shell must search in order to execute any command or file

HOME Stores the default working directory of the user.

LOGNAME Stores the login name of the user.

MAIL Defines the file where the mail of the user is stored.

Defines the duration after which the shell checks whether the user hasreceived any
MAILCHECK
mail .by default value is 600(seconds)
IFS Defines the internal field separator, which is a space, a tab, or new line.

SHELL Defines the name of your default working shell

TERM Defines the name of terminal

TZ Defines the name of the time zone in which we are working

User-defined variables :

• These are defined by us and are used most extensively in shell programming. To define UDV use
following syntax

• Syntax:
variable name=value

• 'value' is assigned to given 'variable name' and Value must be on right side = sign.

• Example:
$ no=10 # this is ok

$ 10=no # Error, NOT Ok, Value must be on right side of = sign. To define variable

called 'vech' having value Bus

$ vech=Bus

To define variable called n having value 10

$ n=10

Rules for Naming variable name (Both UDV and System Variable) :

• Variable name must begin with Alphanumeric character or underscore character (_), followed by
one or more Alphanumeric character. For e.g. Valid shell variable are as follows:
HOME SYSTEM_VERSION vech No

• Don't put spaces on either side of the equal sign when assigning value to variable. for e.g. In
following variable declaration there will be no error
$ no=10

But there will be problem for any of the following variable declaration:

$ no =10

$ no= 10

$ no = 10

• Variables are case-sensitive, just like filename in Linux. for e.g.


$ no=10

$ No=11

$ NO=20

$ No=2

• Above all are different variable name, so to print value 20 we have to use $ echo $NO and not any
$ echo $no # will print 10 but not 20

$ echo $No # will print 11 but not 20

$ echo $No # will print 2 but not 20

• You can define NULL variable as follows (NULL variable is variable which has no value at the time of
definition). for e.g.
$ vech=

$ vech=""Try to print it's value by issuing following command

$ echo $vech

Nothing will be shown because variable has no value i.e. NULL variable.

• Do not use ?,* etc, to name your variable names.

Positional Parameter :

• On many occasions we need to convey information to a program. A very convenient way of doing
this is by specifying arguments at the command line. But how does the shell script know what has
been passed to it?

• For this, the shell uses something called ‘Positional Parameters’. These can be thought of as
variables defined by the shell. They are nine in number, named $1 through $9.

• Consider the following statement, where SS is any executable shell script file and the remaining are
the arguments.

$ SS Pro is to Con as Progress is to Congress :

• On entering such a command, each word is automatically stored serially in the positional
parameters. Thus, $0 would be assigned SS, $1 would be assigned' Pro' , $2 'is' and so on, till
'Congress', which is assigned to $9. These are available to the shell script to use as need be. This is
an extremely useful feature, as we now proceed to remonstrate.

Passing command line argument :

• The knowledge of positional parameters opens up a wider scope to programming, at the same
time makes things easier. Say for instance we have to write a shell script which accepts two file
names from the command line, copies the first file to the second and then displays it.

• SS3 is the answer:


#SS3

# Usage: SS3 <source filename> <target filename> cp $1

$2 cat

$2

• To make it executable, we would change its mode using chmod and then execute it thus:

• $ SS3 machine machine_copy I really hate the dammed machine; I wish that they would sell it,

• It never does quite what I want, But only what I tell It!
• Well, those were the ratings of some woebegone programmer under a cloud, which were stored in
the file machine. Hope he found the silver lining soon. The statement cp $1 $2 is translated by the
shell as cp machine machine_copy, as $1 collected the first argument and'$2, the second.

• Hence machine is copied machine_copy: (which gets created if not already present) and then cat $2
displays its contents. Here is another example. There's no way you can create a file which gives the
owner the execute permission. That’s the reason why we reminded you every time to change the
mode of a shell script before executing it. It's a bit of a nuisance, saying chmod first then executing
any new script. We can substitute the two commands by writing a shell script for new files, which
by itself makes the file executable as well as execute it. Like all good ideas, even this script is a short
and sweet one.
#SS4

# Usage: SS4 <filename>

chmod 744 $1 $1

• Now, for a newly created file, or for any file which does not grant executable permission to
thatowner, SS4 can be used as shown below:
$ SS4 AnyScript

• Whatever the permissions of AnyScript, rest assured that you won't get the 'execute permission
denied' message. $1 is replaced by the shell by AnyScript, it's mode is set to 744, and lastly simply
saying $1 calls AnyScript for execution. Just as files can be executed from the shell prompt, so also
can they be from the shell script.

Arithmetic in Shell Script :

• So far we have seen how to assign values to variable~. Let us now see how we can operate upon
these values. Recall that all shell variables are string variables. If we are to carry out arithmetic
operations on them we have to use the command expr which is capable of evaluating an arithmetic
expression. The following Program shows the various arithmetic operations that can be carried out
using expr.
# SS9

#Usage:

SS9

# Example of arithmetic operations a=20 b=10

echo 'expr $a +

$b' echo 'expr $a -

$b' echo 'expr $a

\* $b' echo 'expr

$a / $b'

echo 'expr $a % $b' # modular division, returns remainder

Output :
30

10
200

How to write shell script

• Following steps are required to write shell script:

• Use any editor like vi or mcedit to write shell script.

• After writing shell script set execute permission for your script as follows

• Syntax : chmod permission your-script-name

• Examples :
$ chmod +x your-script-name

$ chmod 755 your-script-name

• Note: This will set read write execute (7) permission for owner, for group and other permission is
read and execute only (5). (3) Execute your script as:

• Syntax: bash your-script-name sh your-script-name ./your-script-name

• Examples:
$ bash bar

$ sh bar

$ ./bar

• Note: In the last syntax ./ means current directory, But only . (dot) means execute given command
file in current shell without starting the new copy of shell, The syntax for . (dot) command is as
follows

• Syntax : command-name

• Example: $ . foo

• Now you are ready to write first shell script that will print "Knowledge is Power" on screen. See the
common vi command list, if you are new to vi.

Decision making instruction :

• The Bourn shell offers four decision making instructions.

o The if-then-fi statement.

o The if-then- else-fi statement.

o The if-then-elif-else-fi statement.

o The case-esac statement.

The if-then-fi statement :

• If implement the decision control instruction

• Syntax:
if control command

Command 1

fi

• Example:

#SS13

#Usage:ss13

• Enter source and target file names read source target

• if cp $source $target then echo File copied successfully fi

The if-then-else-fi Statement :

• The if statement by itself will execute a single command, or a group of commands, when the exit
status of the control command is O. It does nothing when the exit status is 1. Can we execute one
group of commands if the exit status is 0 and another group if the exit status is 1? , Of course.

• This is what is the purpose of the else statement, which is demonstrated in the following shell

• Example:
# SS14

#Usage: SS14

Enter source and target file names read source target

if cp $source

$target then

echo File Copied

echo Failed to copy the file

• A few points for if then else fi :

• The if statement can be represented by a block as shown below.

• The group of commands between the then and else is called an 'if block'. Similarly, the commands
between else and fi form the 'else block'.
• Notice that the else is written exactly below the if. The statements in the if block and those in the
else block have been indented to the right.

• Unlike languages like C or Pascal, even if there is only command to be executed in the if block the fi
cannot be dropped.

The test Command :

• This command investigates the sort of test that we raised above and then it translate the results
into the language of success or failure this helps shell in deciding whether to execute the command
in the if block or the commands in the else block.

• The test command works simply. If the given expression is true, test exits with a status of zero;
otherwise it exits with a status of 1.

• Example:
# S515

# Usage: 5515

# Demonstrates the use of test command echo Enter a number from 1 to 10

read num

if test $num -lt 6

then

echo I used to think I was indecisive, but now I am not so sure echo -Anonymous

fi

• Output :
$ 5515

Enter a number from 1 to 10 4

I used to think I was indecisive, but now I am not so sure

-Anonymous

Types of test command :

• Numerical tests: used to comparison between two number to be done

• String tests

• File tests

Numerical Test :

• Following are the operator used for numerical test:


Operator Meaning

-gt Greater then

-lt Less then

-ge Greater then or equal to


-le Less then or equal to

-ne Not equal to

-eq Equal to

File Tests :

• The test command has several options for checking the status of the file. These are shown in below
table.
Option Meaning

-s file True if the file exists and has a size greater than 0

-f file True if t he file exists and is not a directory

-d file True if the file exist and is a directory file

-c file True if the file exists and is a character special file

-b file True if the file exists and is a block special file

-r file True if the file exists and you have a read permission to it

-w file True if the file exists and you have a write permission 10

-x file True if the file exists and you have an execute permission to it

-k file True if the file exists and its sticky bit is set

• Example: for file test command # SS17


#Usage: SS17

echo Enter file name read file name

if [ -f $fname ]

then

else

echo you indeed entered a file name

fi

echo what you entered is not a file name

• Example: shows that user has the write permission to a file # SS19
# Usage: SS18

echo Enter file name read filename

if [ -w $filename ]

then

echo Type matter to append. To stop type Ctrl + D.


else

cat >> $filename

fi

echo No write permission.

String Tests :

• This test command is also use for handling the strings tests.

Condition Meaning

string1=string2 True if the strings are same

String1 !=string2 True if the strings are different

-n string True if the length of strings is greater then 0

-z string True if the length of strings is ZERO

string True if the strings is not a null string

• Example: for string test # SS19


# Usage: SS19

str1=”Good”

str2=”Bad”

str3= [$str1= $str2]

echo $?

[$str1 != $str2]

echo $?

[-n $str1]

echo $?

[-z “$str3”]

echo $?

[-z $str3]

echo $?

[“$str3”]

echo $?

• Output :
Nested if-else :

• It is perfectly all right if we write an entire if -else-fi construct within either the body of the if
statement or the body of an else statement. .This is called 'nesting' of ifs.

• This is shown in the following program.

• # SS21

• # Usage: 5S21

• # A quick demo of nesled if-else echo


echo example of nested if-elses

echo Enter either 1 or 2

read i

if [ $i -eq 1 ]

then

echo you would go to heaven!

else

if [ $i -eq 2 ]

then

echo Hell was created with you in mind else

echo How about mother earth!

fi

fi

• Output :

Forms of if :
# First form :

If conditio; then

commands
fi

# Second form :

if condition ; then
commands

else

commands

fi

# Third form:

if condition ; then

commands

elif condition ; then

commands

fi

Logical Operators :

o a (read as AND)

o (read as OR)

o ! (read as NOT)

• The first two operator -a and -o allow two or more conditions to be combined in a test.

else if equals elif :

• It permits you to group together several alternatives one after the other by using keyword elif
which is short form of else if.

• Syntax:
if [ expression 1 ]

then

Statement(s) to be executed if expression 1 is true

elif [ expression 2 ]

then

Statement(s) to be executed if expression 2 is true

elif [ expression 3 ]

then

Statement(s) to be executed if expression 3 is true

else

Statement(s) to be executed if no expression is true

fi
• Example:
#ss24

#Usage: ss24

#Example of nested else's using the elif clause echo “Enter the adapter name \c”

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 :

The case control Structure :

• To controlling the sequence of execution is using the case control structure.

• Syntax:

case word in

pattern1)

Statement(s) to be executed if pattern1 matches ;;


pattern2)

Statement(s) to be executed if pattern2 matches;;

pattern3)

Statement(s) to be executed if pattern3 matches;;

esac

• Example:

FRUIT="kiwi"

case "$FRUIT" in

"apple") echo "Apple pie is quite tasty.";;

"banana") echo "I like banana nut bread.";;

"kiwi") echo "New Zealand is famous for kiwi.";;

esac

• Output :

Loops in shell script :

• A loop involves repeating some portion of the program either a specified number of times or until a
particular condition is being satisfied. There are three methods by way of which we can repeat a
part of a program. They are:

• Using a for statement

• Using a while statement

• Using an until statement

The while LOOP :

• The while statement is used when you want to loop while a statement is true. This is the same in
many other programming and scripting languages. The body of the loop is put between do and
done. Suppose that we want to write a script to have the user guess what number we are thinking
of. The best way to use this would be to use a while loop.

• Syntax:
while <condition>

do

<command()>

done
• The command within the do and done keyword are executes as long as condition evaluates to true.

• Example: To display the number from 1 to 10.


#SS!

A=1

while [$a -le 10]

do

echo $a

A=’expr $A + 1’

done

The until Loop:

• The until loop will execute until the specified condition evaluates to FALSE. Evaluates a condition
at the beginning of the loop and keep iterating until the specified condition evaluates to true.

• Syntax:
until <condition>

do

<command(S)>

done

• Example: To display the number from 1 to 10.


a=1

until [$a -gt 10]

do

echo $a

a=’expr $a + 1’

done

The for Loop :

• Accept the list of variable or expression as input and execute the commands within do and done,
based on the value and expression.

• Syntax:
for variable_name in <list of variable>

do

<command(s)>

done

• variable_name denotes the name of variable list of variable specifies the list of values that
variable name can assume.
• Example:
for var in 0 1 2 3 4 5 6 7 8

do

echo $var

done

• Output :

• Example: For loop with command line arguments


# 5545

# Usage: 5S45 [argl arg2 arg3 arg4 ... ]

for word in $*

do

echo $word

done

• Output :
Let us see what happens when we execute this program.

$ 5545 Meny go round and Tora Tora Tora

Merry go round and Tora Tora Tora

• Now the variable word takes in turn of the arguments supplied at command prompt and echo
echoes these values

Generating Values for a for Loop :

1. Mention the values that the control variable should take immediately after the keyword in as
shown:

for var in moderation is for marks

2. Take the values from shell script arguments as in


#ss1

for var in $* or

#ss1 for var


3. Take filenames from the directory as value for the control variable for file in * .c
for var in $*.c

do

mv $file $file.cpp

done

• This loop would pick up all programs files from the current directory and add the extension*.cpp at
the end of each file.

4. The control variable can take values from a shell variable phrase =”to stay out of trouble”
for word in $phrase

do

echo $word

done

5. The control variable can take values from the output of a command as shown
for cmd in 'cat commandlist'

do

man $cmd >> helpfile

done

• The back-quotes ensure that, the command within the back quotes are replaced with the output of
the command, hence here the 'cat command list would be replaced with the list of commands that
may be present in the file command list. Then these command names would be used as successive
values for the variable cmd, the manual pages for each of these commands are then appended to
the file helpfile.

The break Statement :

• We often come across situations where we want to jump out of a loop instantly, without waiting to
get back to the control-command. The keyword break allows us to do this. When the keyword
break is encountered inside any loop, control automatically passess to the first statement after the
loop.

• Example:
# 5551

#Usage: $$51

pathname pathname=$1

oldifs=”$IFS”

IFS=/

flag=no

sel

$palhname
for dir in $*

do

if [ ! -d $dir ]

then

echo $dir is not a directory ... hence breaking

else out flag=yes

fi break

num=’ls | wc -|’

echo $dir has $num entries

done

if[flag==yes]

then

echo Abrupt end to the for

loop fi

IFS=$oldifs

• In this program the moment the condition [ ! -d $dir] fails (i.e., the value stored in dir is not a
directory entry) the message "not a directory ... hence breaking out" is echoed and the control
breaks out of the while loop.

• There are two ways the control could have reached outside the while loop:

o It jumped out because all the values taken by the for loop have exhausted.

o The loop came to an end on execution of break.

The continue statement :

• In some programming situations we want to take the control to the beginning of the loop,
bypassing the statements inside the loop which have not yet been executed. The keyword continue
allows us to do When the keyword continue is encountered inside any loop, Control automatically
passes to the beginning of the loop.

• A Continue is usually associated with an if. As an example, let's Consider the following program .
# ss53

# Usage: ss53 i=1

white [$i -le 2]

do

j=l

while [$j -le 2]

do

if[$i -eq $j]


then

j='expr $j + 1'

continue

fi

j='expr $j + 1' echo $i $j

done

done

• Output:
13

22

Sign : _______________
Practical : 5 Date :

Aim : Write a shell script to find factorial of given number.

Algo :

• Read The number Say, n.

• Find 1*2*3…*n

• Display the result.

Solution :

Output :

Sign : _______________
Practical : 6 Date :

Aim : Write a shell script that greets the user by saying Good Morning, Good Afternoon and Good Evening
according to the system time.

Algo :

• Get the system time

• Compare system time with values in between 5 to 12, 12 to 4 and 4 to 4.

• Display greetings according to that.

Solution :

Output :

Sign : _______________
Practical : 7 Date :

Aim : Write a shell script to find word in a file.

Algo :

• Read the name of file.

• Read word from user.

• Get the content of file and compare word with it.

• Increment the counter as word find in file.

• Display the result accordingly.

Solution :

Output :

Sign : _______________
Practical : 8 Date :
Aim : Write a shell script that accepts file name as a command line argument and convert its contents in to
upper-case letters.

Algo :

• Get the name of file through command line.

• Read the content of file and convert content into upper case.

• Continue the process till end of file.

• Display the result.

Solution :

Output :

Sign : _______________
Practical : 9 Date :
Aim : Write a shell script to check if the input string is a palindrome.

Algo :

• Read the string from user.

• Reverse the string and store in some another string.

• Compare the original and reverse string.

• Display the proper message according to result.

Solution :

Output :

Sign : _______________
Practical : 10 Date :
Aim : Write a shell script to generate Fibonacci series

Algo :

• Read the number from user.

• Initialize two values with 0 and 1.

• Do the following until condition get true. n3=n1+n2; n1=n2; n2=n3;

• Display the result.

Solution :

Output :

Sign : _______________

You might also like