You are on page 1of 144

99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

UNIT I - LINUX INTRODUCTION & FILE SYSTEM


LINUX OVERVIEW 2
Linux is an
There are operating
several system
distributors of developed
Linux. All for
the business, educational
distributors andkernel.
use the Linux personal use.
Some of An
the
operating
distributorssystem is are:
of Linux a software program that acts as an interface between a user and a
Distributor Web site
computer. TheRedoperating
Hat system manages the computer hardware, system resources, memory
http://www.redhat.com
and the interaction
Caldera between the computer and its users. The operating system also provides a
http://www.caldera.com
platform to Mandrake
develop application software. There are various operating systems, such as Disk
http://www.linux-mandrake.com
Operating System
Debian (DOS), UNIX, Linux, Windows NT, Windows 2000, and OS2. Linux is
http://www.debian.org
SuSE http://www.suse.com
open source software and its distribution
Slackware is governed by the terms of Gnu's Not UNIX
http://www.slackware.com
(GNU) General Public License (GPL).
Linux are
There follows thedistributions
many open development model.operating
of the Linux The source code as
system of various
the Linuxdevelopers
kernel is available
used the
for study
open andavailable
source modifications on the
to develop Internet.
different Therefore,
Linux the current
distributions. Somedevelopment versionused
of the commonly of
Linux distributions
Linux is always open to Caldera,
are: users. Users canDebian,
also suggest modifications to the kernel
andcode.
SuSE.When
• Amusements: Contain games Corel,
and graphic Kondara,
packages Red Hat, Mandriva,
a new version of Linux
• Applications:
Each Linux isemulators,
released,
Containcontains
distribution users can
editors,
packages. work on theand
multimedia
The packages new version
system
available to fix are
inpackages
Linux bugs, if any.into
grouped To
• Development:
maintain
the stability,
following Contains debuggers,
Linus Torvalds
categories: libraries,
ensures strict tools andcontrol
quality systemand
packages
then merges all the new
• System
code environments:
into the Contain
kernel. This is kernel,
in contrast to libraries, daemons
a closed model and shell
in which packages
a project team develops-a
HISTORY
particular OF LINUX
software version and waits before users can work on software and report bugs. The
In 1969,team
Kenthen
Thompson and Dennis Ritchie adeveloped a small,
Thisgeneral-purpose operating
project fixes the bugs and releases new version. is a major reason for the
Linux has an official mascot, the Linux penguin, called Tux, which was selected by Linus
system called UNIX. Traditionally, all operating systems were written in the assembly
success oftoLinux.
Torvalds represent the image he associates with the operating system. Linux has free
language
FEATURESand soOFwas UNIX. In 1973, Thompson and Ritchie rewrote the UNIX operating
LINUX
software, such as text editors, browsers, and programming tools. Figure 1-1 shows the
system in C. In 1974, UNIX was licensed to universities for educational purposes and made
official mascot of Linux:
commercially
Many vendors,available later. IBM, and Hewlett-Packard, purchased the source code of UNIX
such as Sun,
and developed their own version of UNIX. Most of these versions were proprietary and
maintained
No viruses:by theirdoes
linux respective hardware
not recognize vendors.
win32 The source
Executable, code
thereby of these
making versionstowas
it possible not
have a
freely
virus
In available,
free
1984, system.soStallrnan's
Richard the developers
Freehad to waitFoundation
Software for a long time
(FSF)forbegan
the release of bug(GNU
the GNU fixes.
'S Not
Open sources: Unlike Windows, Linux distributions are open source and the source code
UNIX) project to create a free version of the UNIX operating system. The FSF built a
can be edited and modified to the utmost to suit your needs.
number of tools that could be freely used, read, modified, and redistributed. By 1990, the
Better learning: Linux not only teaches you how to install and run a program, but also helps
FSF
In developed
1991, Linus aTorvalds
number of tools butathe
developed kernel
kernel was
and still not
called created.
it Linux. In 1992, the Linux kernel
you do the same using a Terminal. It comes as a tutorial and with its source codes accessible
was combined with the incomplete GNU system to form a completely free operating system.
to all provides an opportunity to understand your machine better and explore further.
Free software:
This operating every
systemapplication and softwarebecause
is called GNU/Linux on Linuxit isisfree band an openofsource.
a combination GNU So andno
more worries
Linux./The about licenses!
GNU/Linux Thissystem
operating makesis the Linux areferred
commonly better alternative to a Windows
to as the Linux operating
application.
system.
Easy to use: the current versions of Linux are very user friendly, and weSigma
SJAHER,MOOLAMATTOM can even say more
Sathyan
friendly than any other OS in ease of use.
3

Linux community help: as Linux is a community product, it has very active system and
24*7 community help for any query related to Linux.
User friendly desktop effects: in the past three years, companies supplying Linux have
stressed heavily on their desktop versions and now it is better than any other OS for home
and office use.
Easy upgrade: Linux gets upgraded through its package manager, and the same goes for its
other applications. Its upgradation feature makes it unique and handy as compared to other
proprietary software.
Highly customizable: customization is strength of Linux and it is because of this very
feature that it is becoming the first choice for any professional.
Experience live: it is another unique feature developed by most Linux companies to provide
a live environment for use. Now Linux is PC independent and you can use it from any
system, anywhere in the world.
Multi-user environment: Linux provides the real multi-user environment, which means
Linux system can support different users with different privileges. In Linux system, each user
has access to a predefined set of system services and their own private data. The private data
in turn can be shared with other users by granting access privilege to them. All the privilege
checking is done with the help of user accounts maintained by the system. This is a unique
Multiprogramming:
feature of Linux, whichAllows
providemany
extra programs
security. to be executed simultaneously by different
users.
Time-sharing: Is a concept that allows multiple programs to share CPU time for their
execution. The programs are placed in a sequence before their execution. Each program gets
CPU time for a specific time period. In that specific time period, the program is executed.
After the specified time period for program execution is expired, the program is put back in
the sequence to wait its turn again. The next program in the sequence is allotted the CPU
Multitasking: Is a concept that enables execution of multiple tasks simultaneously. A
time for its execution.
process in Linux is broken down into tasks. At a time,' each task either reads data from or
writes data to the disk, or waits for input from a user. When a task is waiting for the
completion of an activity, such as getting input from the keyboard, the CPU, instead of
wasting time, starts executing the next task. Therefore, while one task is waiting for input
Virtual
from thememory: Helps
user, another optimize
program thebe
could useinof
theresources,
process ofsuch as read
being memory
from and CPUdisk.
the hard time. The
physical memory may not always be sufficient for executing large applications or activating
multiple applications at a particular point of time. In such situations, Linux makes a portion
of the hard disk, called swap partition, available for use as the virtual memory. The computer
SJAHER,MOOLAMATTOM
keeps the programs and data that are not frequently required on the swapSigma Sathyan
partition and loads
4

them in the physical memory, whenever required. Therefore, it uses the resources of the
computer to the optimum.
Shared libraries: Are a set of functions that are needed by applications to execute programs.
The use of shared libraries helps to save hard disk space and memory because you do not
need to write the code separately for each application. You can create the functions and put
them in the shared libraries so that all applications can use these functions.
Samba: Is a suite of programs that implement the Server Message Block (SMB) protocol in
Linux that helps share a file created on Linux with the Windows operating system. SMB is
the protocol used by the Microsoft operating systems to share file and print services. SMB
also enables the sharing of printers connected to either Linux or the Windows OS.
Network Information Service (NIS): Is a client and server database system that helps share
passwords and group files across the Linux network. NIS server also maintains a central
database of account information that is used for account authentication.
Cron scheduler: Is a scheduler program that is used to run commands, scripts, or programs
at scheduled times.
Office suite: Is a package that supports OpenOffice.org, which is an application program
with several built-in tools. OpenOffice.org helps create documents, spreadsheets, and
presentations.
Data archiving utilities: Are a set of utilities used for data backup. The different data
archiving utilities are: tar, cpio, and dd. Advanced Maryland Automatic Network Disk
Archiver or Amanda is a backup system supported by Linux that uses data archiving utilities.
It enables the LAN administrator in setting up a master backup server and makes back up for
multiple hosts in a large capacity tape drive.
Web server: Is the software that hosts Web pages. Linux comes with the Apache Web
server, which is the most popular Web server in use today.

Licensing: Linux is licensed under the GNU General Public License. This license states that
anyone who wants to use and apply it can do so, and has the right to change linux and
eventually redistribute the changed version, with one condition that the code should be
available after redistribution.ie, you are always free to grab a kernel image for any of your
functions as long as your client can still have a copy of that code.
*Since it is mostly written in C language, it is flexible & portable.

*It provides multilevel file system. The linux file structure is set up according to FHS (File
Hierarchy standard)

*The machine architecture is hidden from the user.

SJAHER,MOOLAMATTOM Sigma Sathyan


5
ADVANTAGES OF LINUX
The Linux operating system provides the following advantages to users:

Linux is free: When we say Linux is free it does not mean it is free of cost; it means Linux is
free to adopt. You can always download Linux from the Internet absolutely for free. There is
no registration fee, no costs for using it and you will still get free updates. The most unique
feature is its freely available source code which you can customize according to your
requirements.
The license commonly used in the GNU Public License(GPL). This license states that anyone
who wants to use and apply it can do so, and has the right to change the Linux and eventually
redistribute the changed version, with one condition that the code should be available after
redistribution. In other words, we can say that you are always free to grab a kernel image for
any of your
Linux functions independent:
is hardware as long as yourThe
client can still have
advantage with aLinux
copy of
is that
that code.
the source code and
documentations are always available. Thus if you find any difficulty in installing Linux in
any hardware, you can easily customize it as per your needs. This makes Linux hardware
independent.
Linux keeps on running: As with UNIX, a Linux system expects to run without rebooting
ever time you can switch on the system. Consequently , there is no boteration of maintaining
standards of performance. This is why many tasks are executed at night or scheduled for
other such calm moments, ensuring higher availability during busier periods and a more
balanced use of the hardware. This property allows Linux to be applicable also in
Linux is secure
environments andpeople
where versatile: Linux for
are pressed hastime.
proven beyond doubt the sound security level it
offers. The security aspect is the key feature of Linux and its security model entirely based on
UNIX, which we all know is very robust and of proven quality. In Linux, security is not only
restricted to, security from Internet threats but is also secure from other system –related
breachesis orscalable:
Linux malpractices.
Linux is created in a way that it is suitable for any application, any
hardware, and any process. From a Palmtop with 2MB of memory to a petabyte storage
cluster with hundreds of nodes, add or remove the appropriate packages and Linux fits all.
• Reliability: Implies the stability of Linux because Linux servers are not shut down for years
together. As a result, using Linux operating system enables you to work consistently with the
Linux server without reporting any operating system failures.
• Backward compatibility: Provides support for the existing hardware. The feature of
providing support for the existing hardware is called backward compatibility.
• Easy upgrade and installation process: Provides menu-driven Installation of Linux. It
also allows you to upgrade from prior versions.

SJAHER,MOOLAMATTOM Sigma Sathyan


6

• Low total cost of ownership: Lowers the cost of ownership because most of the packages
that come with it are available free of cost. The system configuration requirements for
installing Linux, such as speed of processor and amount of RAM required are also very
minimal. As a result, the hardware cost goes down.
• Graphical User Interface (GUI): Is a user interface that helps the users to interact with the
computer easily. The GUI of Linux is X Window system. The X Window system consists of
two subsystems: server and client. Linux has a number of GUIs called Desktop
Environments, such as K Desktop Environment (KDE) and GNU Object Model Environment
(GNOME). Both, KDE and GNOME are versions of the X Window system and run on X
•server.
Excellent security features: Offers security because Linux is free of any virus attack. As a
result, there is more security in Linux as compared to other operating systems. This is the
reason why many Internet Service Providers are replacing their current operating systems
with Linux.
• Support for high user load: Supports a large number of users working simultaneously.
That is why it is used in the organizations where the number of users is large.
• Support for application development: Offers an excellent platform for many development
languages, such as C, C++, JAVA, Python, PHP, and Perl. It also supports Integrated
Development Environments, such as KDevelop and Glade.
IDENTIFYING LINUX PRE-REQUISITES (INSTALLING REQUIREMENTS)
There are various hardware requirements as well as software requirements to install
Red Hat Linux 9 on your computer. You need to fulfill these requirements before installing
Red Hat Linux 9. The requirements include availability of Red Hat Linux 9 software. You
can install Red Hat Linux 9 in different ways, such as using Compact Disk-Read Only
Memory (CD-ROM), downloading it from the Internet, from your hard drive or directly
Hardware
through Requirements
File Transfer Protocol (FTP, NFS, HTTP).
Before installing any software, you need to consider the hardware requirements for
that software. The hardware requirements necessary for successful installation of Red Hat
Linux 9 can be classified as follows:
• Requirements related to CPU: The requirements related to CPU:
- Minimum: Pentium-class, such as Pentium I and Pentium II.
- Recommended for text-mode: 200 MHz Pentium-class or higher version
- Recommended for graphical mode: 400 MHz Pentium II or higher version

• Requirements related to hard disk space: Requirements related to hard disk space:
- Custom Installation (minimum): 475MB
SJAHER,MOOLAMATTOM Sigma Sathyan
7
- Server (minimum): 850MB

- Personal Desktop: 1.7GB


- Workstation: 2.1GB
- Complete Installation (can include all packages available with Red Hat Linux 9): 5.0GB

• Requirements related to memory: The requirements related to memory:


- Minimum for text-mode: 64MB
- Minimum for graphical: 128MB
- Recommended for graphical: 192MB
The various devices, such as display card and sound card that are used in installation must be
compatible with specific installation type and post installation usage.

INSTALLING LINUX

The various steps involved in installing Linux are:

 Selecting the installation method


 Selecting an installation mode
 Checking the installation
Selecting the media type
 Partitioning the hard disk
 Configuring boot loader
 Configuring security settings
 Creating boot disk
Installing packages
Configuring graphics

LINUX & UNIX

Linux was developed using UNIX as a reference model. Therefore, the basic architecture and
features of Linux and UNIX are the same. Linux is considered as another version of UNIX.
The main difference between Linux and UNIX is that Linux is available free of cost. Various
distributors of Linux do charge a price but the price is comparatively lower than other
operating systems. Linux comes with all the development tools you could possibly require to
develop applications. These development tools include the programming languages, such as
C, C++, FORTRAN, Pascal and several scripting languages, such as awk, Perl and Python,
The UNIX operating system requires at least 500 MB of hard disk space. On the other hand,
most of which are free. In addition, Web servers, such as Apache, and browsers, such as
Linux can be installed on a computer having 150 MB of hard disk space and can run on 8 MB
Netscape provide compatible versions for Linux free of cost.
of RAM. The following table compares both Linux & Unix:
SJAHER,MOOLAMATTOM Sigma Sathyan
8

Features Linux Unix


Licensing Freely distributed Expensive licensing
Shells available Bash, pdksh, tcsh, ash Bourne, Korn, C
Distributions RedHat, Caldera, AT&T, Ultrix, SunSolaris,
Debian, SUSE Xenix, IRIX

ARCHITECTURE OF LINUX

Linux architecture consists of the following the software components:


Kernel
Kernel is the core of the Linux operating system. It provides services for all other components
of the operating system. Kernel controls the resources of a computer by allocating them to
different Linux users and tasks. Ie, it decides the user of various resources, for how long and
when. It interacts directly with the hardware. But do not interact directly with a user. Instead,
users can use an interactive program called shell to interact with the hardware. The kernel
controls the resources of a computer and forms an interface between the user and the
hardware.
Shell It is the memory resident portion of Linux and performs the following tasks: I/O
management, process management, device & file management and memory management.
Shell is a user interface that helps a user to interact with the Linux operating system. The shell
provides services requested by Linux users, such as viewing a file and creating or removing a
directory or a file. It hides the complex hardware details from the Linux users. In Linux, shell
is used as a Command Line Interface (CLI) to run commands and programs. Users have no
direct interaction with the kernel; users are interacted with the kernel through shell. The main
Functions
Acts of the Shell
as a mediator are:kernel and the user
between
Shell is a command line interpreter, that interprets user commands and given to the kernel.
Provides services to the user.
I/O Redirection: Reading data from a file instead of reading from a standard input device and
writing the contents to a file instead of displaying it in the standard output device
Pipelining Feature:
Power full Shell allows
programming 2 commands
language: to work
We can write together
shell scriptsby
forconnecting
automatingthose using
various tasks.
pipes (|).
Utilities and Application Programs
The utilities in Linux are collections of programs that provide day-to-day processing
requirements, such as searching a word in a file and viewing access permissions of files.
These programs are invoked through the shell of the Linux operating system.
SJAHER,MOOLAMATTOM Sigma Sathyan
BCA 603(B) LINUX OPERATING SYSTEM 9

The components of Linux architecture interact to process an application or execute a


command. A copy of shell is provided to each user to interact with the Linux operating
system. The shell interacts with the kernel through system calls of Linux. System calls are a
set of routines that enable you to access kernel services for your application programs. A
routine is a sequence of code that is called repeatedly to perform a specified task during the
execution of a program. Linux provides different programs to manage processes, memory,
input/output devices, file and directory services and network. These Linux programs, called
SHELLS AVAILABLE IN LINUX
daemons are always active. If these programs are inactive, you can activate them by using
shell. IN LINUX, the shell runs like any other program. Various shells available in Linux are
as follows:
BOURNE SHELL
The BOURNE SHELL was developed at AT & T and named after its developer STEPHEN R.
BOURNE It is distributed with all UNIX systems and is stored in the /bin directory. The
executable file name for this shell is sh. It is one of the most widely used shells for UNIX
systems.
C SHELL
It was developed by William Joy at the University of California at Berkeley to provide a
programming interface similar to the C programming language. The C shell derives its name
from its programming language, which resembles the C programming language in syntax. The
executable file name for this shell is csh.
SJAHER,MOOLAMATTOM Sigma Sathyan
KORN SHELL 10

It was developed at AT & T and named after its developer David Korn. The Korn Shell
combines the features of both the Bourne and C shells. Its executable file name is ksh.
RESTRICTED SHELL
You use the restricted shell to provide limited access on the operating system to a user. The
restricted shell is typically used for guest users who only need limited rights and permissions.
You can use this shell to restrict the users of the operating system to a limited environment.
BASH SHELL
It is an enhancement on the Bourne Shell, hence the name Bash which is an acronym for
Bourne Again Shell. Bash is product of Free Software foundation‘s GNU project. It is the
default shell for most Linux systems stored in the /bin directory. It stores all of the commands
that you use in a session and also in the previous shell. In Red Hat Linux, the sh command is a
symbolic link to bash.
Tcsh SHELL or TC SHELL
Tcsh stands for Tom‘s C shell and is an enhancement of the C shell. It is also known as the
TC shell. In Linux the csh command is a symbolic link to the Tcsh shell. We can execute the
Tcsh shell by typing either csh or tcsh at the command prompt.
A SHELL
It was developed by Kenneth Almquist of the University of Berkeley.It emulates the Bourne
shell. The A shell is suitable for computers that have limited memory. The executable file
name for the A shell is ash.
Z SHELL
It offers the features of Tcsh and Korn shells. It also provides a large number of utilities and
extensive documentation. The executable file name for the Z shell is zsh.

Feature Bourne Korn C Tcsh Bash


Background processing Yes Yes Yes Yes Yes
Command history No Yes Yes Yes Yes
Yes Yes Yes Yes
I/O redirection
Shell scripts Yes
Command alias Yes Yes Yes Yes
Yes
File name completion No Yes Yes Yes
Yes
Command completion No
No Yes Yes Yes
Yes No
No
Command line editing No No Yes Yes Yes
Yes
Job control
LINUX FILE SYSTEMNo Yes Yes
No Yes Yes
A file system is a group of files and relevant information regarding them. Your whole hard
SJAHER,MOOLAMATTOM Sigma Sathyan
11

disk may comprise a single file system or it may be partitioned to house several file systems.
But the reverse is not true. No file system can be split over two systems. Ie, it provides a
mechanism trough which we can store and organize files in our hard disk.
The disk space allotted to a Linux file system is made up of ‗blocks‘, each of which is
typically of 512 bytes. Some have block sizes of 1024 or 2048 bytes. The block size depends
upon how the file system is implemented on a particular installation. It amt also change from
one Linux version to another.
To check the block size use the following command:
$ cmchk
BSIZE=1024

All the blocks belonging to the file system are logically divided into four parts. The first block
of a file system is called the 'Boot block' which is followed by 'Super block', 'Inode Table'
and'Data Blocks J Let us understand these blocks one by one.
The Boot Block
This represents the beginning of the file system. It contains a program called 'bootstrap
loader'. This program is executed when we 'boot' the host machine. Although only one boot
block is needed to start up the system, all file systems contain one (possibly empty) boot
block.
The Super Block
The super block describes the state of the file system - how large it is, how many maximum
files it can accommodate, how many more files can be created etc. It contains information
like:
a) Size of the file system
b) Number of free blocks on the system
c) A list of free blocks
d) Index to the next free block on the list
e) Size of the inode list
g)
f) Number and list of free inodes
h)
Index
The Inode to the next free inode on the list
Table
Flags to indicate modification of super block
We know that all entities in UNIX are treated as files. The information related to all these files
(not the contents) is stored in an Inode Table on the disk. For each file, there is an inode entry
in the table. Each entry is made up of64_bytes and contains the relevant details for that file.
These details are:
SJAHER,MOOLAMATTOM Sigma Sathyan
12
(a) Owner of the file
(b) Group to which the owner belongs
(c) Type of file
(d) File access permissions
(e) Date and time of last access
(f) Date and time of last modification
(g) Addresses
(i) Number ofoflinks to the
blocks filethe file is physically present
where
(h) Size of the file

Data Blocks
These contain the actual file contents. An allocated block can belong to only one file in the
file system. This block cannot be used for storing any other file's contents unless the file to
which it originally belonged is deleted.
Surrogate Super Block and Inode Table
Judging by the information stored in the Inode Table this must change whenever we use any
file, or change its permissions, etc. Making these changes on the disk would waste a lot of
precious CPU time. To solve this, a copy of the Super Block and Inode Table gets loaded into
memory (RAM) at start-up time. Since memory access is faster than disk access, less time is
consumed in recording the changes in the RAM copies of Super Block and Inode Table every
time some modification occurs. The original SuperBlock and Inode Table on the disk are
updated after a fixed interval of time; say every 30 seconds, by a command called sync. sync
synchronizes the inode table in memory with the one on disk by simply overwriting the
memory copy on to the STRUCTURE
LINUX DIRECTORY disk. Thus, the changes that may have been recorded in the copy in
In Microsoft
memory Windows
during the last almost
intervalallofprograms areget
30 seconds installed in ―Program
duly registered on theFiles‖.
disk. It doesn‘t happen
in the case of Linux.

SJAHER,MOOLAMATTOM Sigma Sathyan


13

Different types of files are placed in the directory structure.


/
Root directory that forms the base of the file system. All files and directories are logically
contained inside the root directory regardless of their physical locations.
Contains the Linux kernel and other files needed by LILO and GRUB boot managers.
/boot
/bin
Contains the executable programs that are part of the Linux operating system Many Linux
commands, such as cat, cp, ls, more, and tar, are locate in /bin
/dev
Contains all device files. Linux treats each device as a special file. All such files are located in

/home
Home directory is the parent to the home directories of users.

SJAHER,MOOLAMATTOM Sigma Sathyan


14

/lib
Contains library files, including loadable driver modules needed to boot the system.
/media
Directory for mounting files systems on removable media like CD-ROM drives, floppy disks,
and Zip drives.
/mnt
A directory for temporarily mounted File Systems.
/opt
Optional software packages copy/install files here.
/proc
/sbin
A specialadministrative
Contains directory in abinary
virtualfiles.
File System. It contains
Commands such as the information
mount, about
shutdown, various
umount, aspects
reside
of a Linux system.
here.
/root
/srv
Home directory
Contains data for of the root
services user. FTP, etc.) offered by the system.
(HTTP,
/sys
A special directory that contains information about the devices, as seen by the Linux kernel.
/tmp
Temporary directory which can be used as a scratch directory (storage for temporary files).
The contents of this directory are cleared each time the system boots.
/usr
Contains subdirectories for many programs such as the X Window System.
/usr/bin
Contains executable files for many Linux commands. It is not part of the core Linux operating
system.
/usr/include
Contains header files for C and C++ programming languages
/usr/lib
Contains libraries for C and C++ programming languages.
/usr/local
Contains files that are shared, like, default configuration files, images, documentation, etc
Contains local files. It has similar directories as /usr contains.
/usr/src
/usr/sbin
Contains the source code for the Linux kernel.
Contains administrative commands
SJAHER,MOOLAMATTOM Sigma Sathyan

usr/share
15

/var
Contains various system files such as log, mail directories, print spool, etc. which tend to
change in numbers and size over time.
/var/cache
/var/lib
Storage area for cached data for applications.
Contains information relating to the current state of applications. Programs modify this when
they run.
/var/lock
Contains lock files which are checked by applications so that a resource can be used by one
application only.
/var/log
Contains log files for different applications.
/var/mail
Contains users' emails.
/var/opt
Contains variable data for packages stored in /opt directory.
/var/run
Contains data describing the system since it was booted.
/var/spool
A command is an instruction given by a user telling a computer to do something, such a run a
Contains data that
single program or aisgroup
waiting
of for some
linked kind of processing.
programs. Commands are generally issued by typing them
/var/tmp
in at the command line and then pressing the ENTER key, which passes them to the shell.
A command
Contains consists
temporary ofpreserved
files a command namesystem
between usually followed by one or more strings that
reboots.
comprise options and arguments.
Linux Each of these strings is separated by white space .The
Commands
general syntax for commands is
command [options] [arguments]

The square brackets indicate that the enclosed items are optional. Most commands have at
least a few options and can accept (or require) arguments. However, there are some
commands that do not accept arguments, and a very few with no options.
COMMANDS FOR FILE AND DIRECTORIES
cd
The cd command, which stands for "change directory", changes the shell's current working

SJAHER,MOOLAMATTOM Sigma Sathyan


16

directory. Type cd followed by the name of a directory to access that directory. General
format is
cd <directory name>
Eg: cd games
If the directory games is not located hierarchically below the current directory, then the
complete path must be written out.
Eg:the
cd current directory
/usr/games
To Eg: cd up
move .. one directory, use the shortcut command. Hence Move to the parent directory of

ls
ls lists the contents of a directory. If no target directory is given, then the contents of the
current working directory are displayed.
General format is
ls [-options] <directory name>
options includes
-a list hidden files
-d list the name of the current directory
-F show directories with a trailing '/ and executable files with a trailing '*'
-g show group ownership of file in long listing
-l long listing giving details about files and directories
-i print the inode number of each file
-R list all subdirectories encountered
-t sort by time modified instead of name
Eg
$ ls
bin dev home mnt share usr var test1.text palindrome.sh
$ ls -l
total 8904
-rw-rw-r-- 1 mca 571 82 Aug 6 2009 12.java

-rw-r--r-- 1 mca 571 160 Mar 31 2011 172.25.60.125

100 Aug 8 13:56 1.cc


-rw-r--r-- 1 mca 571

SJAHER,MOOLAMATTOM Sigma Sathyan


17

WILDCARDS AND GLOBBING


Often, you may need to perform a single operation on many filesystem objects, without
operating on the entire tree as we just did with recursive operations. For example, you might
want to find the modification times of all the text files we created in lpi103-2, without listing
the split files. Although this is easy with our small directory, it is much harder in a large
filesystem.
To solve this problem, use the wildcard support that is built in to the bash shell. This support,
also called "globbing" (because it was originally implemented as a program called /etc/glob),
lets you specify multiple files using wildcard pattern.
A string containing any of the characters '?', '*' or '[', is a wildcard pattern. Globbing is the
process by which the shell (or possibly another program) expands these patterns into a list of
pathnames matching the pattern. The matching is done as follows:
? matches any single character.

* matches any string, including an empty string.

[ introduces a character class. A character class is a non-empty string, terminated by a ']'. A


match means matching any single character enclosed by the brackets. There are a few special
considerations.
 The '*' and '?' characters match themselves. If you use these in filenames, you need to
be careful about appropriate quoting or escaping.

Because the string must be non-empty and terminated by ']', you must put ']' first in
thestring if you want to match it.
characters and all characters between them in the collating sequence. For example, [0-9a-fA-
The '-' character between two others represents a range that includes the two other
F] represents any upper or lower case hexadecimal digit. You can match a '-' by putting it
either
 first
Theor '!'
lastcharacter
within a specified
range. as the first character of a range complements the range so
that it matches any character except the remaining characters. For example, [!0-9] means any
character except the digits 0 through 9. A '!' in any position other than the first matches itself.
Remember that '!' is also used with the shell history function, so you need to be careful to
ls text[!2-4]
properly escape it.

text1 text5 text6

[ian@echidna lpi103-2]$ ls text*[2-4]*

text2 text[2*?!] text3 text4

[ian@echidna lpi103-2]$ ls text*[!2-4]* # Surprise!


SJAHER,MOOLAMATTOM Sigma Sathyan
18
text1 text[*?!1] text[2*?!] text5 text6

cp
cp is used to make copies of files or entire directories. To copy files, use general format :

$ cp [-options ]<source-file(s)><destination file>

where source-file(s) and destination specify the source and destination of the copy
respectively. The behaviour of cp depends on whether the destination is a file or a directory. If
the destination is a file, only one source file is allowed and cp makes a new file
called destination that has the same contents as the source file. If the destination is a directory,
many source files can be specified, each of which will be copied into the destination
directory.
cp myfile yourfile

Copy the files "myfile" to the file "yourfile" in the current working directory. This command
will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if
it exists.
cp -i myfile yourfile

With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.

cp -i /data/myfile
Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt
before overwriting the file.
cp -dpr srcdir destdir

Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-p option),
file attributes (-p option), and copy recursively (-r option). With these options, a directory and
all it contents can be copied to another dir
rm
$ rm [-options]target-file(s)
removes the specified files. Unlike other operating systems, it is almost impossible to recover
a deleted file unless you have a backup If you would like to be asked before files are deleted,
use the -i option:
$ rm -i myfile
rm: remove 'myfile'?
SJAHER,MOOLAMATTOM Sigma Sathyan
19

‘rm’ can also be used to delete directories (along with all of their contents, including any
subdirectories they contain). To do this, use the -r option. To avoid rm from asking any
questions or giving errors (e.g. if the file doesn't exist) you used the -f (force) option. Extreme
care needs to be taken when using this option - consider what would happen if a system
administrator was trying to delete user will's home directory and accidentally typed:
$ rm -rf / home/will

mkdir
Make directory. Syntax is
makdir [-p] <directory name 1><directory name2>

To create a directory, use mkdir followed by directory name

The mkdir command creates a directory called ‗bcas6‘.

$ mkdir bcas6
The option –p allows you to create multiple generations of directories at one go.here
–p tells linux to create works, then within it bpb, next its child directory linux and
lastly book nested within all these.
$ mkdir -p works/bpb/linux/book
To create a directory which should have permissions 754 irrespective of the umask
you can use the command:
$ mkdir -m 754 newdir

rmdir – remove directory


syntax : rmdir <directory name>

The rmdir will remove a directory if it is empty

$ rmdir bcas6
To remove the parent directories of book , we use:

$ rmdir -p works/bpb/linux/book
Here on removing book directory if the linux directory is empty it will be removed
and if the bpb directory falls empty then that too gets removed and so on. This
PWD stops when rmdir bumps into a non empty parent directory.
process
Show the name of the current working directory. The pwd (print working directory) command
will show you the full path to the directory you are currently in.

SJAHER,MOOLAMATTOM Sigma Sathyan


20

$ pwd
more /etc/profile

file
file - determine file type.
This command lists the general classification of a specified file. It lets you to know if the
content of the specified file is ASCII text, data, separate executable, empty or others.
General format is file < filename>

$ file test1.txt
test1.txt: ASCII text

$ file *
amitha_linux.sxw: Zip archive data, at least v2.0 to extract

ample.txt: empty
anand: directory
anupama: directory
aswathy: ASCII C program text
bank_challan.pdf: PDF document, version 1.4
bank.java: ASCII Java program text
Bin:
directory
chardemo.class: compiled Java class data, version 46.0
here * indicates the content of the current directory.

more
Displays the contents of target-file(s) on the screen, pausing at the end of each screenful and
asking the user to press a key (useful for long files). It also incorporates a searching facility
(press '/' and then type a phrase that you want to look for).
You can also use more to break up the output of commands that produce more than one
screenful of output as follows

syntax is more <target-file(s)>


if we have a file of 50 pages which can‘t be displayed at a time. Only the last page
will displayed on the screen, first pages will move very fast. The more command
SJAHER,MOOLAMATTOM Sigma Sathyan
21

solves this problem by displaying the file screen by screen –

$ more stud_details
Roll_no marks
1 44

2 33

3 45

4 56
--More--(01%)
More command pauses when the screen fills and waits for pressing a spacebar key
before it moves to another screenful of text. A message at the bottom of the screen
tells us the percentage of file that has been displayed so far. We can press Ctrl-C to
quit more command before reaching the end of file.
less
The less command works like more except that it moves both forward and backward
in the file while the command is running. We can use the B key on your keyboard to
back up one screen or a spacebar to move forward and display the next screen.
$ less prime1.c

touch
Touch creates files with zero bytes. Doesn‘t allow storing anything in file.
$ touch sample
To create many empty files quickly
$ touch sample1 sample2 sample3 sample4
To create a new file with some data in it – for example, a line of text we use the echo
This will create a file named firstfile with only one line in it MG UNIVERSITY.
command.

cat
$echo MG UNIVERSITY > firstfile

$ cat target-file(s)

displays the contents of target-file(s) on the screen, one after the other

To create a file and add contents to that file


$ cat > test
hello,s6bca...
hows LINUX......
SJAHER,MOOLAMATTOM Sigma Sathyan
22

To display the contents of a file


$ cat test
hello,s6bca...
hows LINUX......
To append some lines to an existing file
$ cat >> test
College will reopen on 29 December 2014
$ cat test
hello,s6bca...
hows LINUX......
cat can concatenate the contents of two files and store them in a third file.
$College
cat sample1 sample2
will reopen on >
29newsample
December 2014
If the output file contains anything it will be overwritten.If you want that content
intact and contents of sample1 sample2 should append to output file use the
$ cat sample1 sample2 >> newsample
append output redirection operator >>
copy
To copy the contents of one file to another one use the following method. If
destination file doesn‘t exist it will be created. If it exists Linux will over write the
contents of destination file.
$ cat > cptest1
ass
sads
aqsdw
as
$ cat > cptest2
12
1323
sads
3543
aqsdw
$ cp cptest1 cptest2
as
$ cat cptest2
We can copy all the file mentioned to the indicated directory, provided the
ass
directory should exist.
$ cp letter.a letter.b letters
SJAHER,MOOLAMATTOM Sigma Sathyan
23

cp: `letters': specified destination directory does not exist

Try `cp --help' for more information.


We can copy file from or to different directories by specifying their name along
with their path.
$ cp /usr/aa16/chapter1 /usr/aa16/newbook/chap1
Here the file chapter1 is copied from the directory /usr/aa16 to the directory
/usr/aa16/newbook. When copied to this directory it would have the name
chap1instead of chapter1.
mv
mv is for moving a file.
Renaming of files in DOS is interpreted in linux as moving them. mv command is
more capable than ren of DOS.
$ mv test2 test3
$ cat test2
$cat test2: No such file or directory
$ cat test3
1
2
The
3 mv command also has the power to rename directories
$ mv vimal works
4
$ cd works/
5
$ ls
$ cd vimal/
bpb vimal
$ ls vimal
ls: vimal: No such file or directory
$ mkdir neewdir
$ mv file23 file24 neewdir
$ cat file23
cat: file23: No such file or directory
$ cat file24
cat: file24: No such file or directory
file23 file24
$ cd neewdir/
$ cat file23
$SJAHER,MOOLAMATTOM
ls Sigma Sathyan
24

q
w
e
$ cat file24
1
3
44
head
55
It is used to display the starting lines of a file and also specifies how many line to display. By
default it will display 10 lines.
Synatx: $ head [options] filename

Options
-n specify how many lines you want to display.
-n number the number option argument must be a decimal integer whose sign affects the
location in file measured in lines
-c number the number option argument must be a decimal integer whose sign affects the
location in file measured in bytes
$ mkdir amitha
If more than one file is given with head command, it will return 10 lines from each file.
$ cd amitha
$ cat test1
qwqeqreq
eqrwqrfw
deawqrdfwsfr
dfsf
sf
fsfsfsgv
fgsdgdgbd
gdgdgb
$ head -3 test1
qwqeqreq
eqrwqrfw
$ head -n 6 test1
deawqrdfwsfr
qwqeqreq
$ head -c 4 test1
SJAHER,MOOLAMATTOM Sigma Sathyan

qwqe
25

eqrwqrfw
deawqrdfwsfr
dfsf
sf
fsfsfsgv
$ cat s1
qw
weret
sdf
dsfdgfs
fsfgsg
$ cat s2
qeer
sfdf
rtyr
cbc
$ head -c 2 s1 s2
==> s1 <==
qw
==> s2 <==
qe
$ head -n 4 s1 s2
==>
sfdf s1 <==
qw
rtyr
weret
cbc
sdf

tail
dsfdgfs
==> s2 <==
It is used to display the last or bottom part of the file. By default it will give 10 lines.
qeer
Syntax: $ tail [options] filename

Options
-n specify how many lines you want to display.

SJAHER,MOOLAMATTOM Sigma Sathyan


26

-n number the number option argument must be a decimal integer whose sign affects the
location in file measured in lines
-c number the number option argument must be a decimal integer whose sign affects the
location in file measured in bytes
$ tail -2 s1
dsfdgfs
fsfgsg
$ tail -c 2 s1 s2
==> s1 <==
g
==> s2 <==
c
$ tail -n 3 s1 s2
==> s1 <==
sdf
dsfdgfs
fsfgsg
FILE
==> s2COMPARISONS
<==
$sfdf
cat file1
hello
rtyr how r u
what
cbc is ur name

$ cat file3
hello how r u
what ar you doing?

cmp
It is used to compare two files. It reports the first instants of differences between the specified
files.ie, two files are compared byte by byte and the location of the first mismatch is
displayed.
Syntax: cmp <filename1><filename2>

$ cmp file1 file3


file1 file3 differ: byte 20, line 2

SJAHER,MOOLAMATTOM Sigma Sathyan


27

comm
It compares two sorted files line by line.

Syntax: comm [OPTION]... FILE1 FILE2


With no options, produce three-column output. Column one contains lines unique to FILE1,
column two contains lines unique to FILE2, and column three contains lines common to both
files.
-1 suppress lines unique to FILE1

-2 suppress lines unique to FILE2

-3 suppress lines that appear in both files


$ comm file1 file3

hello how r u

what ar you doing?

what is ur name
$ comm -23 file1 file3

what is ur name
$ comm -1 file1 file3

hello how r u

diff
$ diff file1 file3
2c2
< what is ur name
---
DISK RELATED COMMANDS
> what ar you doing?

df – disk free
This command reports the free as well as the used disk space for all file system installed in
your machine.df will give output in KB.
$ df
Filesystem 1K-blocks Used Available Use%
Mounted on
97122640 10076428 82112652 11%
/dev/sda3
SJAHER,MOOLAMATTOM Sigma Sathyan
28

/
none 1018144 0 1018144 0%
/dev/shm
To display the output in human readable format, like MB and GB
$Filesystem
df -h Size Used Avail Use% Mounted on
/dev/sda3 93G 9.7G 79G 11% /
995M 0 995M 0% /dev/shm
none
du – disk usage
It is used to find the size of current directory. It gives the list of directories present in current
directory and their size in KB or MB or GB recursively.By default everything in KB
$ du
964 ./share/locale
544 ./share/icons
48
24 ./share/realplay
./share/superbuffer
1876 ./share
12
220 ./.mozilla/default/ontku2i6.slt/chrome
To get output ./.mozilla/default/ontku2i6.slt
in more clear way use -h
$ du -h
4.0K ./newdir
12K
4.0K ./works/vimal/newdirect
./fas
16K ./works/vimal
4.0K ./works/bpb/unix/book
8.0K ./works/bpb/unix
8.0K
8.0K ./.xemacs
./za
16K ./nebila
If we specify a directory then du descends down this directory locating any sub directories
lying in it and reports the blocks used by the directory and the sub directories.
$ du
0 /dev/dev/mapper
0 /dev/snd
0 /dev/disk/by-path
0 /dev/input
/dev/disk
To get the size of whole directory
0
$ du -s
74732
SJAHER,MOOLAMATTOM Sigma Sathyan
29

$ du -sh
73M

ulimit – user limit

It contains a value which signifies the largest file that can be created by the user in the file
system.
$ ulimit
Unlimited

A user can reduce this value by

$ ulimit 1
Here onwards no file can be created whose size is bigger than 512 bytes. Once reduced this
value remains effective till the user doesn‘t log out. This change will be effective only for the
current session and the system will return to its default value when you log out.
An ordinary user can only reduce the ulimit value and is never permitted to increase it. A
super user is an exception to this rule and can increase or decrease this value.
Sigma Sathyan
30

UNIT II ESSENTIAL LINUX COMMANDS


Understanding shells
Shell is a user interface that helps a user to interact with the Linux operating system. The shell
provides services requested by Linux users, such as viewing a file and creating or removing a
directory or a file. It hides the complex hardware details from the Linux users. In Linux, shell
is used as a Command Line Interface (CLI) to run commands and programs. Users have no
direct interaction with the kernel; users are interacted with the kernel through shell. The main
Functions
 Actsofasthe Shell are:between kernel and the user
a mediator
 Shell is a command line interpreter, that interprets user commands and given to the kernel.
 Provides services to the user.
 I/O Redirection: Reading data from a file instead of reading from a standard input device
and writing the contents to a file instead of displaying it in the standard output device
 Pipelining Feature: Shell allows 2 commands to work together by connecting those using
pipes (|).
Power full
 Processes programming
in Linux language:
& Process We can write shell scripts for automating
Fundamentals
various tasks.
Linux is a multiprocessing/multi-user OS, processes are separate tasks with their own right
and responsibilities. A program in execution is called process. All processes communicate
with each other and with the kernel to co ordinate their activities. Linux supports a large
number of Inter Process Communication mechanisms. (IPC)
Scheduler: There are several processes running in memory at any given moment, the CPU
can cater to only one of these processes, as others should wait their turn. There is a program
called scheduler running in memory deciding which process should get the cpu attention and
when.
Linux process states: At any given moment a process in memory can be in any one of the
following states:
1) Submit state: When you execute a program the scheduler submits your process to a queue
called process queue. At this instant the process is said to be in submit state.
2) Hold state: Once submitted the process waits its turn in the queue for sometime. This is the
hold state.
3) Ready state: As the process advances in the queue at some instant it would become the
next one in the queue to receive CPU attention. This is the ready state.
4) Run state: Finally the process gets the attention of cpu and starts execution there by attains
the run state.
31

5) Wait state: some processes might be required to do an I/O operation. Since I/O is a slow
operation the cpu cant lie idle till the time I/O is over. So such processes are put in wait state
until their I/O is over and are then placed in the ready state.
6) Complete state: A process whose execution comes to an end goes into complete state and
is then removed from the process queue. (stopped) The process can be stopped by sending a
Types of processes
signal.
1) ZOMBIE: It is a process that has completed execution but still exists in the process table.
Zombie means an undead person. Once a zombie is removed its process ID and entry in the
process table can then be reused.
2) ORPHAN: It refers to a process whose parent process has finished or terminated. A
process can become orphan during the remote invocation when the client process crashes after
making a request of the server. They generally waste server resources and can leave a server
in problem. Any orphaned process can be adopted by the special init system process. This is
called re-parenting.
3) DAEMON: It is a process that is constantly running in the background. They run without
theprocess
A user requesting them
is born the to doitso.stars
moment They are neither
executing and linked
is dead with
oncea ituser nor a terminal.
terminates. These
For a process
processes
to be born are created
another when should
process the system
giveboots
birth up andThe
to it. remain
new active
processuntil the system
is called is halted
the child or
and the
shut down.
process that starts it is called is the parent.
PID- PROCESS IDENTIFICATION NUMBER
PID refers to the process identification number of the process you wish to find the parent.
When a process is started it is assigned a unique and the next available PID. As soon as it
terminates, its PID is released for eventual reuse. PID starts with 0 and runs up to a maximum
of 32767.When a maximum is reached it count from 0 again.
ps command
To view the PID of any process we use ps at the prompt. It shows the following details:
1) The pid
2) The terminal from which the processes were launched
4)
3) Command
Amount of with
time which the process
the process was started.
has used
The output of ps looks like:

$ ps
PID TT STAT TIME COMMAND
6651 P0 S 0:01 -ksh<\n>
SJAHER,MOOLAMATTOM Sigma Sathyan
32

6661 p1 S 0:00 -ksh

6738 p2 S 0:00 -ksh

7002 p0 S 0:01 elm

7193 p1 R0:0 ps
The output of ps command shows the many fields. Some of them are:
o USER or UID – Process owner
o PID – Process Identification Number
o %CPU – CPU utiliztion of the process
o %MEM – Percentage of memory in KB used by the process
o
o TTY – Terminal(console)
START associated
– Process start time or date with the process
o
o TIME –– Current
STAT Total CPU time
state usedprocess
of the by the process
o COMMAND – Command being executed
o NI - The nice priority number
o PRI – Process Priority Number
o FLAGS – Numeric flag associated with the process
o PPID – PID of the parent process
Some of the options used with ps command are:

a – show processes belonging to all users


e – show process environment variables after the command line field

l – output in long format


u – show user name & process start time
U – show processes being run by specific user

T – show all processes associated with this terminal

t – show processes belonging to a specific terminal

C – show all processes associated with a specific command

Examples:
To find all processes belonging to user Arjun : $ ps U Arjun

To find all processes for all users: $ ps aux


To find the parent process of another process: $ ps –l “PID”

To display all processes owned by the current user: $ ps ux


To display processes of a particular user: $ ps U anu
33
Properties of Processes
A process has a series of characteristics that can be viewed with the ps command. They are:
 Process ID or PID
 Parent process Id or PPID
 Nice number
 User name of real and effective user (RUID & EUID)
 Terminal or TTY
 Real and effective group owner (RGID & EGID)

PSTREE COMMAND

The pstree command shows the processes and parent – child relationship. It displays the
running process in tree format.
kill command
Some of the reasons why you would like to terminate a process in the middle of its execution
are given below:
a) The terminal has hung. A typical e.g.: of this is when you attempt to cat a directory file.
b) The program, which is running, has gone in an indefinite loop and hence is not getting
terminated.
c)
ToThe system
carry performance
out killing has gone
a process below
first note theacceptable limits
PID of the because
process of too
to be many
killed processes
using the ps
command
running in and use kill command.
the background.

$ kill 5001
5001 terminated

$ kill –9 3216
The –9 refers to sure 100% killing. The signal number 9 (sure kill) forcibly terminates a
process.
The kill command with –l option shows list of all kill signals.
$ kill –l
SIGHUP – Hang up
SIGINT – Interrupt
SIGTRAP
SIGQUIT –– Trace
Quit Trap
SIGKILL – kill. This signal can‘t be caught, blocked, ignored.
SIGTERM – software termination. This is often sent before a kill signal is sent.
SIGSTOP – stop. This signal can‘t be caught, blocked or ignored.
34

It kills all instances of Netscape.


Ctrl C – Used as a break key in Linux. It kills, break, and stop the process that is running on
the terminal.
TOP COMMAND
It is used for system monitoring. Other commands used for system monitoring are ps, iostat,
and vmstat. Using top command we can kill the process causing high load on the system
The output shows that processes are listed in descending order of CPU usage. Top always
shows a dynamic list of processes. At the first portion of output it shows the total uptime of
the system, number of users, number of processes running and the total CPU, memory swap
space of the system.
$ top
top - 10:05:19 up 1:07, 1 user, load average: 0.02, 0.02, 0.00
Tasks: 61 total, 2 running, 59 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.2% us, 0.0% sy, 0.0% ni, 99.8% id, 0.0% wa, 0.0% hi, 0.0% si
Swap:
Mem: 3076408k
2036292k total, 0k used,
total, 228100k 3076408k
used, free,free,
1808192k 155120k cached
14660k buffers
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 16 0 3624 548 472 S 0 0.0 0:00.44 init
2 root RT 0 0 0 0 S 0 0.0 0:00.00 migration/0
34 19 0 0 0 S
3 root 0 0 S 0 0.0 0:00.00 ksoftirqd/0
RT 0 0
4 root 0 0.0 0:00.00 migration/1
UPTIME COMMAND
The uptime shows a one line of information including current time, how long the system has
been running, how many users are currently logged on and the system load averages for the
past 1,5, 15 minutes. Its output is same as the first line of the top command
$ uptime
10:04:30 up, 1:07, 1 user, load average: 0.05, 0.02, 0.00

Background Processing
Most of the system processes run in the background, while the user executes their processes in
the foreground. If the user so desires even he can run his processes in the background. The
user can run time-consuming tasks like sorting a huge file and storing the sorted output in a
file in the background. This way he would not be required to wait till the sorting is over to be
able to run the next process. He can immediately concentrate on another task the moment
D

killall command
sorting process is submitted to run in the background.
35
It allows the user to specify a process by name.
To run a process in the background, UNIX provides the ampersand (&) symbol.While
$ killalla Netscape
executing command, if this symbol is placed at the end of the command then the command
will be executed in the; background. When you run a process in the background a number is
displayed on the screen. This number is the PID of the process that you have executed in the
$background.
sort employee.dat > emp.out &
17653
$
The task of sorting the file employee.dat and storing the output in emp.out has now been
assigned to the background, letting the user free to carry out any other task in the foreground.
$ myprogram &

[1] 1364366
nd

The 2 line shows that the background job number is [1],its PID is 1364366, myprogram is
sent to background.
Though the facility to run processes in the background is of great advantage, it comes with a
few limitations too. These are:
a) On termination of a background process no success or failure is reported on the screen.
We can search for the PID in the output of ps to verify whether the process is still running or
has been terminated.
b) The output of a background process should, always be redirected to a file. Otherwise you
would get a garbled screen showing the output of the background process along with whatever
you are doing in the foreground.
c) With too many processes running in the background the overall system performance is
likely to degrade.

The nohup command


d) If you log out while some of your processes are running in the background all these
processes would
To ensure that be
theabandoned halfway
processes that through.
we have This should
executed is natural
notbecause
die evenallwhen
yourwe
processes
log out, are
use
children/grandchildren/great
the nohup command. Usinggrandchildren
this commandofweyour
can sh (shell)
submit theprocess. And when
time consuming we log out
commands in
thethe
sh background,
process dies log
along
outwith
and all its children.
leave the terminal and come next day to see our output ready.
Appropriately, nohup stands for no hang ups. The nohup command's usage is shown below:
$ nohup sort employee.dat > output.emp
Now we can safely log out (without any hang-ups) without our process getting terminated on
17695
logging out. The output would be ready in output.emp which can be verified when we log in
36

next time. If we do not redirect the output of our background process the command acts
intelligently and stores the output in the file ‗nohup.out‘.
$ nohup sort employee.dat &

16779
Sending output to nohup.out

The ‗nohup.out‟ file is always created in the current directory.


If the nohup command is used in a pipeline care should be taken to precede every command in
the pipeline by word nohup as shown below:
$ nohup cat employee.dat | nohup grep ‗Nagpur‘ | sort > address &
12695
Here all processes in the pipeline remain alive when user logout. If not, command which is
not preceded by nohup will die when you log out. If one of the processes in the pipeline dies
the entire pipeline will collapse.
Moving a Process to Foreground

First of all we start an application

$ FTP Client
Press Ctrl Z to stop the current job. The following command will run the music player
application:
$ xmms
Press Ctrl Z to stop the current job. The following command will compile a c program:
$ gcc Fibonacci.c
Press Ctrl Z to stop the current job. The following command will display the jobs in the shell:
$ jobs
[1] stopped FTP Client
[2] stopped xmms
[3] stopped
The following command gcc
will bring the FTP Client process in the fore by job number 1.
$ fg 1
Changing Process Priorities
Though all processes are equal, some processes are more equal than others. They can be made
so by increasing their priority. The processes with higher priority would obviously get a time
slot earlier and would be fired earlier than the other processes in the queue.
The priority of a process is decided by a number associated with it. This number is called
37

'nice' value of the process. Higher the nice value of a process lower is its priority. The nice
value of a process can range from 0 to 39, with 20 as the default nice value of a process. Thus,
a process with a nice value 25 would execute slower than the one with a nice value 20.
Let's try to increase the nice value of one of our processes.

$ nice cat employee.dat


This would increase the nice value of our cat process from 20 to 30. Since, we didn't specify
the increment, an increment of 10 got assumed and the nice value got correspondingly
incremented. We can specify the value of the increment.
$ nice -15 cat employee.dat
Now the cat process will have a nice value 35 (20+15). Note that the increment range from 0
to 19. By incrementing the nice value we are putting cat on a lower priority and hence it
would be executed slower than what it does normally. It's only the super user who can put a
process on a higher priority by reducing its nice value. The super user can reduce the nice
$ nice -10 sort employee.dat > output.dat
value of a process as shown below:
If your process is going to be time consuming and is going to degrade the system
performance, then you should always run the process in the background with a higher nice
value. Priority of a process can be changed at the time of firing the process at the command
prompt. Once the process has been submitted to the process queue its priority can‘t be
changed. To see the nice values of various processes running in memory use ps –l command.
time command
A command with a higher nice value indeed runs slower than normal. For this we can employ
the time command. It helps us to figure out the time taken to execute a command.
$ time ls -laR > dirlist.out
real 0.3

user 0.0

sys 0.1
Note that in the above command we have redirected the output of ls so that it doesn't mix up
with the output of the time command. The output of time command doesn't get redirected
since the output of the time command is written to the standard error device, i.e. the screen.
The 'real' time in the above output represents the time taken by the command to execute
since its initiation to its termination. The 'user' time represents the amount of time that the
command/program took to execute its own code. For small programs which take milliseconds
to execute, this time is often reported as 0.0, as in the above case. The 'sys' time represents
theSJAHER,MOOLAMATTOM
time taken by Unix to fire the command. Sigma Sathyan
38
Let's now time the same command by executing it with a higher nice value.

$ time nice -19 ls laR > directlist.out

Note that this time the process consumes a significantly higher time to execute. However, the
time taken (user time) by the command to execute its own code has remained same.

Scheduling Of Processes
Linux can schedule processes to get executed within next few-seconds to next few years.
Once the user-has submitted a process to 'Linux directing it to execute the process at a
specified time and date in future, there onwards Linux takes over. Linux manages to
remember the processes to be executed and goes about executing them whenever the time
arises without needing any further directions from the user. That's the philosophy of
$ ps -e | grep cron
scheduling processes. Execute the following command:
147 ? 0:01 cron
Here the process cron stands for chronograph. This system process is responsible for
scheduling the other processes. Neither user nor super user can execute the executable file
(/etc/cron) of this process directly. During booting Linux executes this file and displays the
message 'cron started' on the host terminal. Once Linux launches this process there onwards
cron is activated once every minute. When cron wakes up it checks whether any scheduled job
is available for it to execute. If it is, it executes the job and goes back to sleep again, only to
wake up the next minute to once again carry out the check. This cycle goes on till the Linux
The isn't
system at command
shut down on the host machine. There are three commands which make use of the
cron command
This daemon's scheduling
is capable capability.
of executingThese
Unixarecommands
at, batch and
at a crontab.
future date and time. The Unix
commands can be specified at the command prompt or can be stored in a file and the at
command can use this file to execute the commands.
$ tty
/dev/tty3c
$date
Fri Jun 14 10:57:23 IST 1996
$ at 17:00
clear > /dev/tty3c
echo "It's 5 PM ! Backup your files and logout" > /dev/tty3c
Ctrld
Job 803108760.a at Fri Jun 14 17:00:00 IST 1996
SJAHER,MOOLAMATTOM Sigma Sathyan
39

On pressing Ctrl d the at command displayed the job-id and the date and time we requested
the two commands clear and echo to be executed. The job-id always terminates with a '.a'
indicating that this job was submitted using the at command. Once submitted this way, the
message would be echoed on our terminal at 5.00 PM sharp. It is necessary to redirect the
output of dear and echo to our 'tty' file. Otherwise the output of these commands would arrive
$ at 17:00
as mail from the cron daemon. Let us see:
echo "It's 5 PM! Backup your files and logout"
Ctrld
Job 853158864.a at Wed Jun 14 17:00:00 IST 1996
At 5 PM in the evening you would see a message on your screen saying 'you have mail'. To
examine what have you received in mail just type
$ mail
There are two options available with the at command which permit us to view the list of jobs
submitted using at and to remove any unwanted jobs from this job queue. These options are -1
for listing jobs and -r for removing jobs. While removing a submitted job its job-id should be
mentioned.
$ at –r 853158864.a
would remove the job '853158864.a' from the job queue.
While specifying the time at command permits a lot of flexibility. Following are some of the
specifications that can be used with at:
$ at 0915 am Mar 24
$ at 9:15 am Mar 24
$ at now + 10 minutes
$ at 7now
pm+Thursday
1 day next week
Instead of specifying the commands at the prompt, here we would make at read them from a
file and then execute them. Let's first create this file.
$cat > cmdfile
clear
echo "Hi there! Do you never get bored with working?"
Ctrld
Now we can ask the at command to read the commands from cmdfile as shown below.
$ the
Now at 5at
PM < cmdfile
command willJob
read853158870.a at Fri
the commands fromJuncmdfile
14 17:00:00 IST 1996
and execute them at 5 PM. Since
we have not redirected the output to our terminal it would be mailed to us by cron. System
SJAHER,MOOLAMATTOM Sigma Sathyan
40

administrator keeps tracks of two files at.allow, at.deny. Only those users whose login name
appears in these files are permitted to use the at command. He can edit these two files i.e., to
include
atq :or delete login names.
list the users pending jobs unless the user is the super user; in that case
everybody‘s job are listed. The format of output lines (one for each job) is jobno,date,
hour,jobclas.
atrm : delete jobs, identified by their job number.

The batch command


Using batch command the system decides the best time for executing our commands. Since
the time of execution of our commands is left for the system to decide we don't specify the
time while executing the batch command.
$ batch
sort employee.dat | grep Nagpur > addresses.out
Ctrld
Job 692322435.b at Fri Jun 14 17:00:00 IST 1996
Once again note that the 'b' extension given to our job-id signifies that it has been submitted
using the batch command.
The crontab command
cron is used to execute the commands or programs on a regular schedule including backup,
recovery, copying or any other activity. It is basically called a CRON DAEMON where cron
is an automatic task manger.
Though at and batch are powerful tools for scheduling processes, both suffer from an obvious
limitation. Once jobs submitted using these commands have been executed, the jobs will have
to be rescheduled if they are to be carried out again. For example, if we want to backup all our
C program files at the end of the day then we may do so as follows
$ at 5 PM
cp *.c ./cbackup
However, we must remember to issue such an at command every morning to be able to take
backups every evening without fail. If we forget to do so the backups won't be taken. crontab
can carry out a submitted job every day for years together, without needing any prompting
from us. The jobs can be carried out on a regular basis using the crontab command as shown
$ crontab cmdfile
below:

However, this time cmdfile should not only contain commands which we wish to get executed
but also the details of date and time in a specific format. This format is shown below:
Minute Hour Day of Month Month of year Day of week Command

SJAHER,MOOLAMATTOM Sigma Sathyan


41

Using this format let us create our cmdfile.


$ cat > cmdfile
30 10 1 * * echo "Work hard on first day of the month"
0 0 17 11 * mail aa? < confi.letter

$ Ctrl d

Let us understand the commands that we have given in our cmdfile. The first one would be
used to echo the message at 10:30 am on first day of every month. th The second message would

mail that
Note the contents
each fieldofinthe file confi.letter
cmdfile to the
is separated user
either byaa2 on 17
a space or aNovember of'Month
tab. For the every year.
of year'
and 'Day of week' fields we have used a' *'. A '*' means all possible values. Another thing to
note is that Sunday
is represented as 0 in the 'Day of week' field.
When we execute the crontab command using the cmdfile
$ crontab cmdfile
the contents of cmdfile are automatically transferred to the /user/spool/cron/crontabs
directory where they are stored in a file which has the same name as your login name. There
onwards the cron daemon will read this file and execute the commands present in it on a
regular basis. As with the at command we can view the commands that we have submitted by
using the -l option
$ crontab -l with the crontab command.
To remove the submitted job we can use $ crontab -r
Here we are not required to specify the job-id since using crontab we can submit only one
command file. If we want to schedule a few more jobs we need to edit the cmdfile in our
home directory and then resubmit it using
$ crontab cmdfile
Once again cmdfile‘s contents would be transferred to /usr/spool/cron/crontabs directory
and would be stored in a file with our login name. Obviously the earlier file with this name
would be overwritten. As with at, here also there are two files cron.allow and cron .deny
which decide which users are permitted and which are prevented from using the crontab
command.
Redirecting input/output
In all OS there is a standard input device and a standard output device. In Unix also standard
input device is keyboard and standard output device is monitor (display screen). The standard
error device is also the display screen.

SJAHER,MOOLAMATTOM Sigma Sathyan


Stream Device Value
Standard Input 0 42
Keyboard
Standard Output Terminal Screen 1
Standard Error Terminal Screen 2
Unix and Linux allow you to change the standard input and output temporarily by using
redirection and piping.Redirection is the process of changing the assignment of standard input
device, standard output device, and standard error device. There are three types of redirection:
Input redirection, Output redirection, Error redirection.
Sometimes it is useful to redirect the input or output to a file or printer. You may have to
redirect a directory listing to a file. Unix and Linux provide redirection symbols for this
purpose:
The symbol > implies redirection of output. It sends the output of a command to a file or a
device like printer.
The symbol < implies redirection of input. It takes the input needed for a command from a
printer or file rather than from the keyboard.
The symbol >> adds output from a command to the end of a file without deleting the
information already in the file.
Examples:

1) $ cat file1 > file2


On executing this you will be returned to the $ prompt. The output redirection operator >
makes file2 to be standard output. The output of cat command, which is normally sent to
screen, is sent to file2 and not to screen. If the file file2 doesn‘t exist it is created. If it exists it
is wiped clear and refilled with the new data. Thus the output going to screen is redirected to a
file.2) The Unix manual says that cat reads from the standard input if no input file is given.

$ cat
Linux is open software. It was first
designed by Linus Torvalds.
Ctrl d
Linux is open software. It was first
designed
First by cat
we typed Linus Torvalds.
and then hit the Enter key. We didn‘t provide any input file name. Then
what we typed was gathered as standard input, and cat passed it on to the standard output
(screen).
3) Any command that accepts standard input also accepts input redirection.

$ cat < newfile


hai, how are you??
Hope you are all fine.
SJAHER,MOOLAMATTOM Sigma Sathyan
43

Here the file newfile became the standard input, and cat read its contents and displayed them
on the screen. The same thing can be achieved by saying,
$ cat newfile
hai, how are you??
Hope you are all fine.
Though both the commands produce the same output there is a difference between the two. In
nd

the 2 case newfile was not the standard input. The standard input remained the terminal, and
the internal programming of cat caused the newfile file to be opened in addition to the
4) Cat can read the standard input and a file input during the execution of the command. The
standard input.
standard method is to use a hyphen – instead of a file name to stand for the standard input.
Here is an
nd example that uses the file newfile as the 1st input and the standard input (screen) as

the 2 input.
$ cat newfile –
ABCD
Ctrl d
hai, how are you??
Hope you are all fine.
st
ABCD
Catkeyboard
concatenated the two by
input denoted inputs. Since the
the hyphen filename
– was printed.came 1 , it was printed first then the

5) We can use both the redirection operator at once.

$ cat < currentfile > newfile


st

The 1 part of redirection, <currentfile , indicates that input is to be taken from the file
nd

currentfile and the 2 part of redirection, > newfile establishes that output is to be routed to
The order in which the two-indirection operators are used doesn‘t matter.ie,
the file newfile.
$ cat > newfile < currentfile
also produce same result.
6) Another redirection operator used is the append operator >>. It is similar to > except if the
target file already exists, the new output is appended to its end.
$ who >> logfile
This command appends the current list of users who have logged in to the end of logfile.
Redirection is a very powerful tool and is frequently used to redirect the output of a process
running in the background.
SJAHER,MOOLAMATTOM Sigma Sathyan
44

There are a few more redirection operators, used mainly in writing shell scripts rather than at
command prompt. They are as follows:
Operator Action
> file make file the std output
< filemake file the std input
>> file make file the std output, appending to it if it already exists.

<< word take shell input up to the first line containing word or up to end of file
make file the output for file descriptor n
n > file
cmd1 | cmd2 redirect
make standard output
standard outputof to
cmd1 the standard
standard error input of cmd2
1>&2
Connecting processes with pipes
Redirection helps to commands to files. Piping facility lets us connect commands to other
commands and operations. To send the output of one command as input to another command,
the two commands must be joined using a pipe symbol (|)
It is possible to join commands using a pipe since many commands accept input from standard
input and send output to standard output. Such commands are known as Filters.
A filter is a program that takes input from the standard input file, processes it and sends the
output to the standard output file. Linux provides various filters like cat, grep, wc, tr cut etc to
enable you to for
Examples work effectively with data.
piping:
1) $ ls | wc -l
Here the output of ls becomes the input to wc which counts the number of lines it receives as
input and displays this count on the screen. Instead of displaying this count, if we want to
store the count value in a file, use the output redirection as shown below:
$ ls wc –l > countfile
This example shows that piping and redirection can go together.
2) $ who | sort
Here, instead of displaying the output of who on the screen it is piped to sort. sort sorts
whatever
$ who | itsort
receives as input (output of who, in this case) and displays the sorted output
> sortedlist
(sorted
3) $ according
who | sort to first character
-logfile in each line) on the screen. Once again, if we want we can
> newfile
redirect this from
The output sortedwho
output to a filethe
becomes by saying,
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 thethesorted
4) Unix offers output is to
tee command redirected
achievetothis
thepurpose.
file newfile.
It reads the standard input and sends
it on to the standard output. It also redirects a copy of what it has read into the file (if any) of
your choice. For example:
SJAHER,MOOLAMATTOM Sigma Sathyan
45
$ 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.
If we want to store the output of who in two files and still manage to send one copy to sort.
$who the
Mention | teetwo
logfile newlogfile
filenames | sort
after the tee command as shown below:
5) We want to store the output of who in filel and file2, display the same output on the screen
and store the sorted output in file3. It can be done:
$ who | tee filel file2 /dev/tty3a | sort > file3
Here, in addition to filel and filel we have used the file associated with our terminal
(/dev/tty3a). Hence tee sends the output of who to all the three files. What is sent to
/dev/tty3a is promptly displayed on the screen. The copy which is sent to sort is first sorted
and the sorted output is then stored in the file file3.
6) 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 filel 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.
7) We can however also redirect the standard error. The following example shows this can be
done.
$ cat myfile > newfile 2> errorfile
If the file myfile exists, then the contents of that file would be copied into newfile. If it does
not exist, then an error message would be produced. Instead of displaying the error message
on the screen it would be redirected to a file errorfile. Note that the > symbol redirects the
Assuming
standard that whereas
output the file myfile did not the
2>redirects exist let's check
standard out the
error. contents
While of errorfile.
redirecting the standard
$ cat
output errorfile
instead of > we may as well use 1>.
cat: cannot open myfile
This is the error message produced by the cat command when it failed to locate the file
myfile. Obviously, had myfile existed its contents would have been copied into the file
newfile.
Printing commands
lp command – It is used to send the user‘s print job to the print queue. When we submit the
job for printing using lp command, it returns a request id. This id can be used to keep track of
our job or to cancel it if required. lp adds a banner page at the beginning of our print out so
that we could identify our print out from large number of users.
SJAHER,MOOLAMATTOM Sigma Sathyan
46

$ lp file1 file2
request id is lp –32(2 files)
Using –w option with lp we will informed if the print job is completed. If we logout before the
completion of print job we will be informed through mail.
$ lp –w file1 file2
request id is lp –44(2 files)
lpstat command - We can watch the status of our print job using lpstat command. The –t
option with lpstat gives status of all print jobs on the queue, type of printer, whether it is
accepting any fresh prints requests etc.
$ lpstat –t
To cancel a print job uses cancel command.

$ cancel lp –13
where lp –13 is the request id of our print job. The cancel command responds with:
request ―lp –13,190 canceled
Options used with lp:
-w sends a message to user when file is printed
-n num prints num number of copies. Default is 1
-o nobanner doesn‘t print the banner page
-P list prints the page numbers specified by list
-d printer specifies a printer other than default printer
The-qprint
levelschedulersets
called lpsched
apriority levelmanages the job.(
for the print printLowest
jobs submitted
is 39) to print queue. It is
usually executed at the time of booting. If not system admin can run this by saying: #
/usr/lib/lpsched
The system admin can terminate print services by using the command: # /usr/lib/lpshut

lpr command - We can also use lpr command in Linux to get a hard copy of the document.

$ lpr projectrep.doc
The lpr command makes a copy of our file and pushes it in the system‘s print queue. This
process is called spooling, so we can change or delete the original file without harming your
printout.
Options used with lpr:
-r tells the system to delete the file after printing.
-s tells the system top print directly from the original file instead of spooling to the print
queue. With this –s option we can‘t modify or delete the original file while it is printing. It is

SJAHER,MOOLAMATTOM Sigma Sathyan


47

useful in saving a bit of time since no copy is made when the original file is big.
$ lpr –r report delete the file report after printing.

$ lpr –s report print the file report without spooling


print the file report without spooling and then delete it.
$ lpr –r –s report

pr commnad- Convert text files for printing. Paginate or columnate FILE(s) for printing.
It displays the contents of the specified file adding with suitable headers and footers. It can be
used with lpr command for neat hard copies. The header part consists of last modification date
and time along with filename and page number.
Syntax:
pr [option]... [file]...

where options can be,


-l <number> It changes the page size to specified <number> of lines (by default the page
size is 66 lines)
-<number> prepares the output in <number> columns
-n Numbers lines
-t turns off the heading at the top of the page.
$ cat e1
1005
1002
1003
1001
$1004
pr e1
2012-01-06 09:40 e1 Page 1
1005
1002
1003
1001
----Note that remaining lines are empty--------
1004
$ pr -n e1
2012-01-06 09:40 e1 Page 1

SJAHER,MOOLAMATTOM Sigma Sathyan


48

1 1005
2 1002
3 1003
4 1001
----Note that remaining lines are empty--------
5 1004
$ pr -3 e1

2012-01-06 09:40 e1 Page 1


1005 1003 1004
1002 1001
----Note that remaining lines are empty--------
$ pr -t e1
1005
1002
1003
1004
1001
find command
You use the find command to locate a file in a specific directory and in all its subdirectories.

Syntax : find [path] expression


When you use the find command, you need to specify the path where the files are located.
You also need to specify an expression. The expression consists of options that affect the
execution of the find command. To perform an advanced search, you can use these options:
Theyou
–name option
use the -name option to specify the name of the files that you need to locate.

Example:
$ Find /home/Steve -name "jan"

/home/Steve/2000/jan
/home/Steve/2001/jan
Here /home/Steve is the name of the directory in which specific files need to be located. The –
name ―jan‖ option specifies that all the files with the name jan are to be located. Consider the
file hierarchy of the /home directory.

SJAHER,MOOLAMATTOM Sigma Sathyan


49

When you use the command with out –name option, the command displays the path names of
all files in the specified directory and its subdirectories. It is shown below:
$ find /home/Steve
/home/Steve/2000
/home/Steve/2000/df
/home/Steve/2000/jan
/home/Steve/2000/feb
/home/Steve/2000/temp
/home/Steve/2001
/home/Steve/2001/df
/home/Steve/2001/jan
/home/Steve/2001/temp
/home/ Steve/ Desktop
/homeSteve/progs
/home/Steve/progs/a. out.
/home/Steve/progs/report

The –type option


You use the -type option to locate a specific type of file. Consider the command given below:

$ find- /home/Steve -type f


SJAHER,MOOLAMATTOM Sigma Sathyan
50

The option f with -type searches for all the ordinary files. To search for directory files, you
need to type the following command:
$ find /home/Steve -type d

The –exec option


You use the -exec option to specify the operations that need to be performed on the files that
have been located by the find command. For example, you can remove all the files that are
named temp from all the directories under a specific directory. To do this, you need to type
the following
$ find command:
. -name temp -type f -exec rm {} \;
In the above command, each ordinary file named temp is to be removed from Steve's current
directory and all its subdirectories.
When you use the -exec option, you need to specify the {} in the syntax. The find command
replaces the {} with the path names of the files, which are located by the command, and each
file is removed. As a part of the syntax, you also need to specify the backslash followed by a
semicolon at the end of the -exec option to specify the end of the command.
The –ok option
You use the -exec option to execute a command on each file located by the find command.
You can also use the -ok option to operate on the files that are located. When you use the -ok
option, the command prompts the user for a confirmation before executing the command for
each file. of the -ok option is similar to that of the -exec option.
Syntax

Example:
$ find . -name temp -type f -ok rm {} \;

To locate the file dmesg, you need to type the following command:
$ find / -name dmesg
To view the contents of the contents of the file, you need to type the following command
$ find / -name dmesg -exec cat {} \;

File processing commands

wc command
It counts the number of lines word and characters in the specified file or files. It comes with
options –l, -w, -c that allows the user to get the number of lines, word, and characters
individually or in any desired combination.
$ wc –lc file1 file2
file1 20 571
file2 30 804
SJAHER,MOOLAMATTOM Sigma Sathyan
51

Thus the file1 contains 20 lines, 571 characters. File2 contains 30 lines and 804 characters.
The wc command is capable of accepting input directly from the keyboard. By entering wc
without arguments, it waits for the user to type in the input. On terminating input (using ctrl
d), [mca@chavara
the appropriate ~]$
counts
wc are displayed for the input that you supplied.
bca bba bcom
mca mba mcom
3 s3 9
s1 s2 35
sort command
It can be used for sorting the contents of a file. It can merge multiple sorted files and store the
result in the specified output file. Sorting is done according to the ASCII collating sequence.
$ sort myfile
This would the sort the contents of myfile and display the sorted contents on the screen.

$ sort file1 file2 file3


It will sort the contents of several files at one shot.

$ sort –o result file1 file2 file3


The above command sorts the 3 files file1, file2, file3 and saves the result in a file called
result.
$ sort –u –o result file1 file2 file3
Using –u option we can avoid repeated lines in each files.

$ sort –m file1 file2


If the files were already been sorted we can merge them using the above command.

$ sort – file1
Sometimes we may want to combine the contents of a file with the input from the keyboard
and then carry out the sorting, using the above syntax. Here - stands for standard input
keyboard.
$ sort
We can even sort only the input from standard input by the above format. Since no file has
been specified here it is assumed that the input is to come from the standard input device.
Sort is used most fruitfully for files which are essentially databases, or which its information
arranged in fields. We can specify the fields for sorting. Such fields are known as sort keys.
The syntax of the sort command includes optional +posl and -pos2, signifying the starting and
ending position of the sort key. If -pos2 is not included, then the key is assumed to extend till
the end of
Assume thea line.
that file students has four fields, for roll number, names of the students, their marks,

SJAHER,MOOLAMATTOM Sigma Sathyan


52

and their grades. These fields would be numbered 0, 1, 2 and 3.


$ sort -r +1 -2 students
Saying thus would sort the file students on the field containing the names of the students. The
+1 indicates that the sort key begins at the second field and the -2 indicates that it ends before
the third field. This yields names of the students as the sort key. We can even have multiple
sort keys using this feature of the sort command.
The -r switch indicates a reverse sort. So, the records arranged in reverse alphabetical order of
names would be displayed on the screen.
If we want to sort the same file according to marks we must use the -n option which specifies
that the sorting is to be done on a numeric field. If not specified then the marks 100, 40, 50, 10
would be incorrectly sorted in the order 10, 100,40, 50.
The options used with sort are:
-m <file list> Merges sorted files specified in <filelist>
- o < f i1ename> Stores output in the specified <filename>
-r
Sorts the content in reverse order (reverse alphabetical order
-u
removes duplicate lines and display sorted content
-n
-1" char " Numeric sort
Uses the specified "char" as delimiter to identify fields
-c Checks if the file is sorted or not
+pos Starts sort after skipping the pos th field

-pos stops sorting after the pos th field


th
+pos.n
Starts sort after the nth column of the (pos+1) th field
-pos.n
Stops sort after the n column of the (pos+1) th field
cut command
This command cuts or picks up a given number of character or fields from the specified file.

Examples:
1) $ cut –f 2,7 empinfo
A database table empinfo contains many fields. The above cut command selects/displays
2nd.7 field and its details.
th

2) $ cut –f 2-7 empinfo

Displays fields from 2 to 7


3)
$ cut –f 2,7 -d ―:‖ empinfo

SJAHER,MOOLAMATTOM Sigma Sathyan


When fields are separated by characters other than the default tab use –d option which allows 53

us to set the delimiter. Ie, database may be as

Name : Age: Addr: City: State:


4)
$ cut –c 1-15 empinfo
Here the cut command can also cut specified columns from a file and display them on the
standard output. The option used is –c. Here the first 15 columns from each line in the file
empinfo would be displayed.
5) $ cat myfile
ANUSHA
ANNA
ARYA
$ cut –b 2, 3 myfile
ANU
ARY
ANN
$ cat emp
1 aa 9
2 bb 8
3 cc 76
4$ dd
cut -c 1,3 emp
1 AA
2 BB
3 CC
4 DD

$ cut –c 1-4 emp


1
2
3

paste4command
This command concatenates the contents of the specified files into a single file vertically.
(Like cut command separates the columns, this paste command merges the columns.)
Syntax
$ paste <filename1><filename2>
[mca@chavara ~]$ cat >e1
1005

1002
SJAHER,MOOLAMATTOM Sigma Sathyan
54

1003
1001
1004
$ cat >e2

computer

zoology

commerce

computer
botany
$ paste e1 e2
1005 computer

1002 zoology

1003 commerce

1001
1004 botany
computer

join command
This command is used to join lines of two files on a common field. It displays a line for a pair
of input lines in which one line is from file1 and other from file2. Both of them have same
value in the join field.file1 and file2 should be already sorted in increasing order of their join
fields.
$ cat file1
1 ANU

2 BINU

3 PAUL

4$ catANN
file2
2 FIRST

4 SECOND
7 CAMEL
$ join file1 file2 > file3

2 BINU FIRST
4 ANN SECOND

SJAHER,MOOLAMATTOM Sigma Sathyan


55

who
Since Linux is a multiuser system ‗who‘ will display the users are currently logged on.
[mca@chavara ~]$ who
mca tty1 Dec 19 13:57

mba tty2 Dec19 14:20


tty3 Dec19 14:24
msw
who am i : It tells who you are (working on the current terminal)
[mca@chavara ~]$ who am i
mca tty1
Dec 19 13:57

Mathematical commands
factor
Print the prime factors of each NUMBER. Print the prime factors of all specified integer
NUMBERs. If no arguments are specified on the command line, they are read from standard
input.
[mca@chavara ~]$ factor 2
2: 2
[mca@chavara ~]$ factor 12
12: 2 2 3
[mca@chavara ~]$ factor 13
13: 13
[mca@chavara ~]$ factor
15: 3 5
a
expr
factor: `a' is not a valid positive integer
It
+ is used to perform arithmetic operations on integers.
Addition
[mca@chavara ~]$ factor
15 -* Subtraction
Multiplication
/ Division (decimal portion will be truncated,division is done only on integers, gives the
quotient only)
% Remainder of division (modulus operator)
A white space must be used on either side of an operator. The * operator has to be escaped to
prevent the shell from interpreting it as the filename metacharcter. So use \ before the *
character.
SJAHER,MOOLAMATTOM Sigma Sathyan
56
[mca@chavara ~]$ x=5

[mca@chavara ~]$ y=2


[mca@chavara ~]$ expr $x + $y
7
3[mca@chavara ~]$ expr $x - $y
[mca@chavara ~]$ expr $x \* $y  Escape the multiplication operator.
10
[mca@chavara ~]$ expr $x / $y
2  note that decimal portion is truncated.
[mca@chavara ~]$ expr $x % $y
1  Remainder part of division.
[mca@chavara ~]$ expr $x + 10
15
bc
[mca@chavara ~]$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software
with ABSOLUTELY NO WARRANTY. For details type `warranty'.
30  result is displayed on the screen
+ 20 
10 Press ctrl arithmetic expression
d to end work
[mca@chavara ~]$ bc
82 / 3  decimal portion is truncated.
By default bc performs truncated division. If you do not want to truncate any value, then you
have to set scale to the number of digits of precision before the operation.
[mca@chavara ~]$ bc
scale = 1
8/3
2.6
2.66
scale =2
8 / ^d
3
Note that the result (2.66) is not rounded off; the actual result is 2.6666….
The bc command can be used with ibase (input base) and obase (output base) to convert
numbers in one bash into another.
$ bc
ibase = 2  set ibase to binary(2)
101  type the input in binary number
SJAHER,MOOLAMATTOM Sigma Sathyan
57

5  result in decimal
$ bc
obase = 2  set obase to binary
5  type the input in decimal number
101  result in binary.
$ bc
ibase = 16  set ibase to hexadecimal
B  type the input in hexadecimal number
11
$ bc  result in decimal
obase = 16  set obase to hexadecimal
11  type the input in hexadecimal number
B  result in hexadecimal
bc also supports functions like sqrt,sine,cos tec.
$ bc
sqrt(169)
13
To find sine, cosine etc use bc –l
$ bc -l
s(0)
0
c(0)
1.00000000000000000000
$ bc –l
s(3.14)
Creating and editing files with vi editor.
.00159265291648695254
Text Editors
scale = 2 A text editor is a program that enables you to create and modify text files.
Typically,
s(3.14) a text editor provides a screen with a fixed line length and line numbers. You can
type
0 text line by line, navigate through the documents by using different commands, and save
the document.
A text editor is usually less preferred by users over a word processor because a word
processor offers additional features, such as text formatting. You can use a text editor to:
  Create andprograms
Create edit documents.
and utilities.
 Write e-mail messages.

SJAHER,MOOLAMATTOM Sigma Sathyan


Functions of a Text Editor 58

Typically, a text editor enables you to perform the following functions:


 Create files: You can use a text editor to create, edit, and save files.
 Open files: You can open, modify, and save an existing file in a text editor. You can also
open multiple documents at a time by using a text editor.
 Copy text: Text editors facilitate document creation because they enable you to copy and
paste text.
 Search for text: In a text editor, you can search for a particular expression or a word. In
case you do not remember the expression to be searched for, you can use wildcard characters
to look for the expression. In addition, many text editors provide the search and replace
Editors Available with Linux
feature. The search and replace feature enables you to change multiple instances of a
Typically, each operating system (OS) includes a text editor. There are various editors
particular word or a string.
available with Linux. Some features that distinguish various editors are interactivity, online
help, and the speed of operation. Some of the various editors available in Linux are also
discussed.
The vi Editor
The visual editor, popularly known as the vi editor, is one of the most widely used UNIX-
based text editors. It offers a compact interface and enables you to control the system by using
the keyboard. The vi editor is commonly used to enter and edit source code and write short
Thesuch
notes, vimasEditor
e-mail messages.
The visual editor improved or vim editor is an enhanced version of the vi editor. The vim
editor includes various enhancements over the vi editor, such as syntax highlighting,
command-line editing, and online help. The vim editor can be used to edit ASCII text. It is
especially useful for editing programs.
The emacs Editor
Another widely used text editor is the edit macros or emacs editor. The emacs editor provides
a much larger set of commands than the vi editor. You can use the emacs editor to format
source code for programming languages, such as C and C++. To enable users to access
information about commonly used commands, the emacs editor displays an online help
The ed Editor
screen.
You can use the line editor or ed. to create, display, modify, and save text files. When you
start the ed editor with a file name as an argument, a copy of the file is created in the editor's
buffer. You can make changes only to the copy of the file and not directly to file. To save the
changes to a file, you use the w command.

SJAHER,MOOLAMATTOM Sigma Sathyan


The red Editor 59

You can use the restricted editor or red to edit files in the current directory. You cannot
execute shell commands by using the red editor.
The joe Editor
Another popular editor available is the Joe's own editor or joe. You can invoke the joe editor
by typing joe at the command prompt. You can also give a file name along with the joe
command to open the file in the editor. The joe editor is a fu'1-screen editor that lets you edit
both programs and text.
The pico Editor
The pico editor is based on the Pine messaging system. The Pine messaging system is a
character-based interface in Linux. You can use the Pine messaging system to send and
receive e-mail messages. The pico editor offers various features, including paragraph
justification and search features. In addition, the pico editor provides a spelling checker and a
file browser. In the pico editor, commands are displayed at the bottom of the screen. The pico
editor also offers context-sensitive help. Among the above editors; vi and emacs are the most
Vi editor
widely used.
It is ascren oriented text editor developed by Bill Joy in 1976.Commands are entered through
keyboard. We can also use mouse support and a GUI version with scrollbars and menus can
be activated.
Disadvantages of vi editor
1) The user is always kept guessing. There are no self explanatory error messages.
2) There are no online help available in vi editor.
3) In each 3 modes of operation, each key pressed has different meanings. So each key press
effect has to be minimized.
4)5) ViItishandles
case sensitive.
files thatA‟h‟ moves
contain text. the
Youcursor one position
can create to files
files, edit the left.
andAprint
„H‟them.
positions it at
the
6)top
It left
can‘tcorner.
do boldface, running headers or footers, italics.
Modes of operation
1) Command mode: To switch to command mode Press ESC key. Here all keys pressed
by the user are interpreted as commands. The keys that are hit are not displayed on the screen.
2)
Insert mode:
replacements of text.It In
is activated by the
insert mode pressing „i‟. Itwe
characters allows insertion
type are addedoftonew text,Itediting
the file. is alsoand
known as input text mode.
3) The ex command mode: It permits us to give commands at the command line. The
bottom line of the vi screen is called the command line.vi uses command line to display
messages and commands. All commands entered in this mode are displayed in the command
line. It is so called because commands given in this mode are compatible with the commands
ofSJAHER,MOOLAMATTOM
the ex editor. Sigma Sathyan
60

Running vi

To run vi and create a new file, simply run the command 'vi' from any shell prompt:
$ vi

Alternatively, to load an existing text file into vi, run the command 'vi [filename]', from the
shell prompt: $ vi myfile.txt

Your file will be loaded into vi, and the cursor will be placed at the beginning of the first line.
Note that an empty line is shown as a tilde (~).

Some basic editing commands

The cursor keys

Probably the most basic and most commonly used commands are those used to move the
cursor around the screen. The cursor is the 'pointer' to the current position in the text, and is
usually represented as a flashing underscore character.
To move the cursor around the screen, you must be in command mode. On some systems, you
may use the standard 'cursor keys' on your keyboard to move the cursor. However, on many
systems, this will not work. This mainly due to historical reasons, dating back to when not all
terminals had cursor keys. If cursor keys do not work on your system, then use the following
keys instead:
h - Cursor left
j - Cursor down
k - Cursor up
l - Cursor right
Deleting a character

While you are in insert mode, you can delete a character that you have just typed by using the
'backspace' key - this is similar to most other editors and word processors. But there is a
difference: You may only delete characters that you have entered in this session of insert
mode.
Repeating a command

What if we wanted to delete a whole batch of characters? For example, if we had 20


characters to delete, it would take 20 key presses. vi provides a simple way of performing this
- in fact, many commands can automatically be run a given number of times.

SJAHER,MOOLAMATTOM Sigma Sathyan


61

To repeat a command, simply type the number of times to run the command before the
command itself. For example, to delete 20 characters from a file, starting from the current
position, using the command '20x'. Note that the command does not appear at the bottom of
the screen, so you have to keep track of what you're typing yourself.
Deleting a line

Just one more command to learn for now. We've seen how to delete a single character with the
'x' command. There is a quicker way to delete an entire line: with the 'dd' command.

vi command summary
The following tables contain all the basic vi commands.

Starting vi

Command Description

vi file start at line 1 of file


vi +n file start at line n of file
vi + file start at last line of file
vi +/pattern file start at pattern in file
vi -r file recover file after a system crash

Saving files and quitting vi

Command Description
:e file edit file (save current file with :w first)

:w save (write out) the file being edited


:w file save as file
:w! file save as an existing file

quit vi
:q
:wq save the file and quit vi

:x save the file if it has changed and quit vi


:q!
quit vi without saving changes

SJAHER,MOOLAMATTOM Sigma Sathyan


Moving the cursor
62

Keys pressed Effect


h left one character

l or <Space> right one character


k
up one line

bj or <Enter> left one


down word
one line
w right one word
(
start of sentence
)
{ end of sentence

} start of paragraph
1G
end of paragraph
nG line n
top of file
G end of file
<Ctrl>W first character of insertion

<Ctrl>U up ½ screen
down ½ screen
<Ctrl>D
up one screen
<Ctrl>B
down one screen
<Ctrl>F
Inserting text

Keys pressed Text inserted


a after the cursor
A after last character on the line

i before the cursor


I before first character on the line
o open line below current line
O open line above current line
Changing and replacing text

Keys pressed Text changed or replaced

cw word

SJAHER,MOOLAMATTOM Sigma Sathyan


63

3cw three words

cc current line
five lines
5cc
current character only
rR
current character and those to its right
s
current character
S current line
~ switch between lowercase and uppercase

Deleting text

Keys pressed Text deleted


x character under cursor
12x 12 characters

X character to left of cursor


dw word
3dw three words
to beginning of line
d0
d$ to end of line
dd current line
5dd five lines

d{ to beginning of paragraph
d} to end of paragraph
:1,. d
to beginning of file
:.,$ d
to end file
whole of file
:1,$ d
Using markers and buffers

Command Description
mf set marker named ``f''
`f go to marker ``f''
´f go to start of line containing marker ``f''
"s12yy copy 12 lines into buffer ``s''

SJAHER,MOOLAMATTOM Sigma Sathyan


BCA 603(B) LINUX OPERATING SYSTEM 64

"ty} copy text from cursor to end of paragraph into buffer ``t''
"ly1G copy text from cursor to top of file into buffer ``l''
"kd`f cut text from cursor up to marker ``f'' into buffer ``k''
"kp paste buffer ``k'' into text
Searching for text

Search Finds
/and next occurrence of ``and'', for example, ``and'', ``stand'', ``grand''
?and previous occurrence of ``and''
/^The next line that starts with ``The'', for example, ``The'', ``Then'', ``There''
/^The\> next line that starts with the word ``The''
/end$ next line that ends with ``end''

/[bB]ox next occurrence of ``box'' or ``Box''


n repeat the most recent search, in the same direction
N repeat the most recent search, in the opposite direction

Searching for and replacing text

Command Description
:s/pear/peach/g replace all occurrences of ``pear'' with ``peach'' on current line

:/orange/s//lemon/g change all occurrences of ``orange'' into ``lemon'' on next line


containing ``orange''
:.,$/\<file/directory/g replace all words starting with ``file'' by ``directory'' on every line
from current line onward, for example, ``filename'' becomes
``directoryname''
:g/one/s//1/g replace every occurrence of ``one'' with 1, for example, ``oneself''
becomes ``1self'', ``someone'' becomes ``some1''

Matching patterns of text

Expression Matches
. any single character
zero or more of the previous expression

SJAHER,MOOLAMATTOM Sigma Sathyan


65

. zero or more arbitrary characters


\< beginning of a word
\> end of a word
\ quote a special character
\ the character `` ''
^ beginning of a line
$ end of a line
[set] one character from a set of characters

[XYZ] one of the characters ``X'', ``Y'', or ``Z''


[[:upper:]][[:lower:]]* one uppercase character followed by any number of
lowercase characters
[^set] one character not from a set of characters
[^XYZ[:digit:]] any character except ``X'', ``Y'', ``Z'', or a numeric
digit

Miscellaneous Commands

Type: To:

Ctrl-g show line number of current line

redraw the entire display


Ctrl-l
fork a shell; type Ctrl-d to get back to vi
:!sh
. repeat last text change command at current cursor position

Options to the: set command

Option Effect
all list settings of all options
ignorecase ignore case in searches
list display <Tab> and end-of-line characters
mesg display messages sent to your terminal
nowrapscan prevent searches from wrapping round the end or beginning of a file
number display line numbers
SJAHER,MOOLAMATTOM Sigma Sathyan
66

report=5 warn if five or more lines are changed by command


term=ansi set terminal type to ``ansi''
terse shorten error messages
warn display ``[No write since last change]'' on shell escape if file has not
been saved

To open multiple files in vi editor- $ vi file1 file2 file3

Block commands

As their name suggests these commands work on a group of lines (a block of text) rather than
an isolated line. For example we may want to delete a group a group of lines from the file by
using a single command. Or we may want to copy a group of lines from one part of the file to
another. We can make block commands to work on single lines. To be able to use block
commands we must remember two things:
(a) All the block commands work in ex command mode
(b) Line numbers should be associated with the text before we issue any block commands.
This is so because block commands need to be told the line numbers on which they are
supposed to operate.
For example, a block command like :4,12d indicates that lines 4 to 12 should be deleted from
the file currently loaded in vi.

While issuing this command if the line numbers are displayed on the screen, we can promptly
issue block commands. To display line number: you have to give a command (Esc) :set
number or (Esc) :set nu in the ex command mode. Once line numbers are displayed we can
issue block commands:
:2,4d deletes line numbers 2 to 4

:5,8 co 15 copies line numbers 5 to 8 after line number 15

When you don‘t want to use block commands and no longer want line numbers to be
displayed use

(Esc): set nonumber or (Esc): set nonu

Various block commands used are as follows

SJAHER,MOOLAMATTOM Sigma Sathyan


67

Command function

:nd Deletes n* line.


:m, n d Deletes lines from m to n.
:n mo p Moves line n after line p.
:m, n mo p Moves lines m to n after line p.
:m co p Copies line m after line p.
:m,n co p
:m, n w filename Copies lines m to n after line p.

:m, n w » filename Writes lines m to n to a file.


: r filename Reads thelines
Appends contents
m to noftothe file filename at current
a file.
cursor position
:r !command
Executes shell command and output of the com-
mand is read at the current cursor position.

abbr is for Abbreviate

In most common editors like wordstar we can use shorthand characters for commonly
required expressions. These shorthand commands can be invoked at the press of a single key
for users convenience.
In vi we can use abbr for this purpose; which stands for abbreviation. We often use printf in
C program.We can abbreviate printf as pr for convenience. For this we have to do:

(Esc) :abbr pr printf

Now when you type the program and you press „p‟ followed by „r‟ they appear on the screen
as they are. But if you follow them with a space or the Enter key the instantly overwritten by
the word „printf‟.
To see the entire list of macros that you have set you use the command: (Esc) :abbr
When not required you can unabbreviated it as follows (Esc) : una pr

Command Function

:abbr<abbreviation><longform> An abbreviation is defined for a long


form. When we type the abbreviation
followed by a space, it is replaced with
:abbr Lists currently
its long form defined abbreviations
:una <abbr> Unabbreviates the abbreviation.

SJAHER,MOOLAMATTOM Sigma Sathyan


68
Command line Options in vi

$ vi + 100 file Loads file and places the cursor on the 100th line in the file.

$ vi +/pattern file Loads file and places cursor on the first occurrence of matching pattern.

Displays file in read only mode of vi. Any changes made to the buffer
$ view file
will not be allowed to be written to the file.

Delete & Paste


vi being a powerful editor it can undo the last nine deletions. Vi maintains registers (buffers)
in memory in
which it can remember the user‘s changes and deletions. Using these registers it can retrieve
the last nine deletions made by a user.

RELATIVE AND ABSOLUTE PATH


One dot'.' represents the current directory while two dots '..' represent the parent
directory.
" cd -" will return us to the previous directory.
We can also use cd absolute path or cd relative path (see below):

ABSOLUTE PATHS
An Absolute Path is easily recognized from the leading forward slash, /. A Slash (/) means
that we start
at the top level directory and continue down.
For example to get to /home/users, we will type:
$This is an absolute path because we start at the top of the hierarchy and go downwards from
cd /home/users
there.
RELATIVE PATHS
A Relative Path do not have a preceding slash. We use a relative path when start from a
directory below
the top level directory structure. This is dependent on where we are in the file system.
For example if you are in root's home directory and want to get to /root/kerala, you type:
$ cd kerala
We can also use absolute addressing as -
# ls /usr/bin
This command lists the files in /usr/bin directory using absolute addressing.
SJAHER,MOOLAMATTOM Sigma Sathyan
TO DISPLAY only file size  $ du –s –h filename
69
UNIT 3 SYSTEM ADMINISTRATION

Role of System Administrator


The various jobs that a system administrator has to carry out are classified as follows:

The prime role is user administration (set up and maintain user accounts)

To maintain smooth running of system


To check that the peripherals are working properly.
To manage hardware and arrange timely repair of hardware in case of any failure.

To monitor system performance to the utmost.


To create file systems as per the organizational requirements.

To install software as per the organizational requirements.


To formulate and administer the back up and recover policy to counter any crisis or loss of
data.
To mange network communication for better coordination among users.
To keep updating systems as soon as anew version of OS or application software is released.

To implement security policies for use of the computer system and network.
To formulate security policies for users. A system administrator must have a strong grasp of
computer security. (Firewalls and intrusion detection systems)
The system administrator can carry out these jobs in 3 ways:

Using sysadmsh, the system administrator shell


Using various system administration tools that come with the system.

Writing small shell scripts which in turn use the tools (system admin tools).
Common Administrative Tasks
The Common Administrative Tasks can be classified as:
System automation which includes: the free disk space checking and reporting periodic
backups, data for the system performance, user account maintenance (creation, deletion etc),
Business specific functions (pushing data to a web server, running monthly/quarterly/yearly
report, etc.)
Documentation: A good system administrator should document Policies, Procedures, and
Changes.

SJAHER,MOOLAMATTOM Sigma Sathyan


70

Communication: A good system administrator should be a good communicator too. All the
users should be aware of at least three points about a system administrator: what he is going to
do, what he is doing, what he has done.
Identifying Administrative Files Configuration and Log files
Linux files are grouped according to their functionality and usage, so there are separate
directories for configuration and log files.
Configuration files: The directory for such file is the /etc directory. Most of the configuration
files resides in the /etc directory. Some of them are as follows:
/etc/passwd contains user password and login configurations

/etc/shadow contains user encrypted passwords.


shells installed on the system that users can use.
/etc/shells
/etc/printcap contains a list of each printer and its specifications.
Log files: The directory for such files is the /var directory. We can use log files to help
tracking the different problems.
System logs name File name Description
BootLog boot.log contains messages indicating which systems services have
started & shut down successfully and which have failed to start an stop.
CronLog Cron Contains message from Crond, a daemon that periodically
runs scheduled jobs like backups.

Managing User Accounts – Adding & Deleting Users.

Adding users with useradd command

$ useradd login_name _of_ user


Example: $ useradd meera
Options used with useradd

Options Meaning
-c comment provide a description of new user account. Usually the person‘s full

name. Replace comment with name of user account.


-d home_dir
Set home directory to use for the account.
-f days Sets the number of days an account remains active after its password

expires.
SJAHER,MOOLAMATTOM Sigma Sathyan
71

-e mm/dd/yy Set an expiry date for account.(none by default)

-m Creates users home directory if it doesn‘t exists.


-M
Doesn‘t create user‘s home directory
-p passwd Enter a password for the account you are adding. (encrypted password)

-u userid Sets user id of the new user.


Sets login shell for new user, default is BASH shell.
-s shell

Examples
$ useradd –c ―MarySmith‖ mary
To create we have to login as root user. Here a new user MarySmith with login name mary is
created.
$ passwd mary
Changing password for user mary

New password:******
Retype new password : ******
$ useradd –m –g users –G wheel, sales –s /bin/tcsh –c ―MarySmith‖ mary
The useradd command is told to create a home directory for mary (-m), make users the
primary group she belongs to (-g), add her to the groups wheel and sales and assign tcsh as her
primary command shell (-s).
Modifying users with usermod command
Use the usermod command to modify user accounts. You must provide account details to
change followed by login name of the account.
Options used with usermod

Options Meaning
-c comment change the description field of the account
-d home_dir change the home directory of the account, with-m option copy the contents
of home directory. Replace home_dir with full path to new directory.
-e expir_date Assign a new expiration data replacing expire data with date in mm\dd\yy.
-f inactivity Set the number of days after a password expires until the account is Permanently

disabled.

SJAHER,MOOLAMATTOM Sigma Sathyan


72

-g group Change the primary group that the user is in replace group with name of
new group.
-G g Set the list of groups that user belongs to. Replace group list with a list
of groups.
-l login_name change login name of account to the name supplied after –l option.
-m This option is used only in conjunction with –d option. It causes the contents

of users home directory to be copied to new directory.


-O This option is used only in conjunction with –u option. It removes the

restriction that user IDs must be unique.


Examples
$ usermod –l jenny –c ―jenny barnes‖ –m –d /home/jenny mary
This converts the mary account to a new name ‗jenny‘ ,new comment (-c ―jenny narnes‖) and
home directory (-d /home/jenny)
To change to tcsh shell $ usermod -s /bin/tcsh jenny or $ chsh -s /bin/tcsh

Deleting users accounts with userdel command


The userdel command takes a single argument which is the login name of the account to
delete. Use –r option to delete user‘s home directory and all files in it.
Examples
$ userdel mary delete user account with login name mary
$ userdel –r mary To wipe out mary’s home directory along with her account.
Files owned by the deleted user but not located in the user’s home directory will not be
deleted. The system administrator must search for and delete those files manually using the
find command.
Creating and managing groups, modifying group attributes

groupadd command
With groupadd command you can create new groups. When you add a group to the system,
the system places the group‘s name in the /etc/group file and gives it a group ID number. This
command creates the group category. Users are individually added to the group.
Examples
To create a group called engine. $ groupadd engines

groupdel command

SJAHER,MOOLAMATTOM Sigma Sathyan


73

You can delete a group with the groupdel command. To delete a group engines use the syntax:

$ groupdel engines
groupmod command
You can change the name of a group or its ID using the groupmod command. Enter
groupmod –g with the new ID number and the group name. To change the name of a group
use the –n option. Enter groupmod –n with the new name of the group, followed by current
name.
$ groupmod -n trains engine.
Here the engine group is changed to new group name trains.

The following example creates a directory called ‗engines‘ and changes its group to that of the
‗engines‘ group.
$ mkdir /home/engines
$ chgrp engines /home/engines
Then the read, write execute permissions for the group level should be set:

chmod g +rwx /home/engines


Any member of the engines group can now access the /home/engines directory and any
shared files placed therein. This directory becomes a shared directory for the group.
$ chgrp engines mymodel
It changes the group for mymodel file to engines.

$ cp mymodel /home/engines
It copies the mymodel file to the /home/engines directory

$ chmod g +rw /home/engines/mymodel

It sets the group read and write permissions to the engines group.

Note:
Red Fat user Manager provides you a Graphical User Interface (GUI) to add, modify view
delete users and groups from Linux OS. To open the Red Hat Manager you need to type the
command at the shell prompt:
$ redhat-config-users
You can also invoke the Red Hat User Manager from the GNOME desktop by selecting

Main Menu Users and Groups.

SJAHER,MOOLAMATTOM Sigma Sathyan


74

Creating and Mounting file system


Creating file systems
Before any partition or disk is used as file system, it is initialized first, and actual data
structures need to be written to the disk which keeps track of all the records on the disk. This
process is called making a file system.
A file system is either the device file associated with the partition or device or is the directory
where the file system is mounted. The basic requirement to mount a partition or to use a
partition is that the file system must first be installed on it by using ext2. This is also a process
of creating inodes and data blocks.
This process of formatting the partition as similar to MSDOS‘s format command in
Windows. In Linux the command to create a file system is called mkfs. The command is
issued in the following way:
mkfs [-c] [-t fstype] fisystem [blocks]
Example
mkfs -t ext2 /dev/fd0  Make a ext2 files system on a floppy

where: -c forces a check for bad blocks


-t fstype specifies the file system type. The shorthand for most file system types.
mkfs –t ext2 can also be written as mke2fs or mkfs.et2 and mkfs –t vfat or mkfs –t msdos can
also be written as mkfs.vfat, mkfs.msdos or mkdosfs
Remember that creating a file system on a device with an existing file system will cause all
data on the old file system to be erased.
Mounting file systems
The meaning of Mounting is to attach the newly created File System to the currently
accessible File System in Linux.
On Linux or other UNIX – like OS, the directory structure begins with the root directory,
which is the directory that contains all other directories and files on the system and is referred
by a forward slash (/). The currently accessible file system is the file system that can be
accessed at given
To get time without
the access of files special programming
on a storage or settings.
device user must first direct the Linux where to
mount the device. A device for mounting can be a partition (a logically independent section)
on a HDD, Floppy Disk, CDROM, and USB Key Drive, Tape Drive or any other external
media.
For example, to get the access of files on a CDROM, user must direct the Linux to make the
file system on the CDROM appear in some directory, typically /mnt/cdrom (which already
exists for this very purpose).
SJAHER,MOOLAMATTOM Sigma Sathyan
75

Mount Point refers to the empty directory in the currently available file system with
which a newly created or additional file system is mounted. It then becomes the root directory
of the added directory tree. This tree is accessible from the directory to which it is mounted
known/mnt
The as the mount point.
directory already exists in Linux by default on all Unix like systems. This
directory with its subdirectories like /mnt/floppy , /mnt/usb are intended specifically to be
used as mount points for removable media such as CDROMS, USB key drives and floppy
disks.
Mounting can be done by the root user by using the mount command with the name of
the device to be mounted and its mounting point / destination.
For eg: to mount the second partition on the first HDD , which is designated by /dev/hda2
, using a directory named / BCA as the mount point we use - $ mount /dev/hda2/BCA
We can remove the connection between the mounted device and the rest of the file
system. This process is called Unmounting. It is done by executing the umount command,
followed by the name of the device to be detached or unlinked and its mount point. For eg : to
umount the second partition from the root file system We use the command:
$ umount /dev/hda2/BCA
An updated list of the devices that are mounted on the Linux can be seen at the /etc/fstab
file. This text file also displays the mount points and other information about the devices. It
can be viewed by using the command
$ cat /etc/fstab

Note
Use the command ls –i to check the inode number of a file.
$ ls – i Myfile
Output : 534634 Myfile
We can also use stat command to find out inode number and its attributes. $ stat Myfile
Output:
File: Myfile
Size : 1988 Blocks : 8 IO Block : 4096 regular file
Device: 341/833d Inode :32820 Links : 1
Access : (0644/-rw-r—r--) UID : ( 0/ root) GID : ( 0/ root)
Access : 2009-11-10 01:16:01.00000000 +0530

Modify : 2009-10-27 13:26:56:00000000 + 0530


SJAHER,MOOLAMATTOM Sigma Sathyan
76
Change : 2009-10-27 13:26:56:00000000 +0530

DISK PARTITIONS & SIZE


1 Concept: Disks and Partitions
 A hard disk provides a single large storage space
 Usually split into partitions
 Information about partitions is stored in the partition table
 Linux defaults to using partition tables compatible with Microsoft Windows
 For compatibility with Windows, at most four primary partitions can be made
 But they can be extended partitions, which can themselves be split into smaller logical
 Extended partitions have their own partition table to store information about logical partitions
partitions
2 Disk Naming
 The device files for IDE hard drives are /dev/hda to /dev/hdd
 hda and hdb are the drives on the first IDE channel, hdc and hdd the ones on the second
channel
 The first drive on each channel is the IDE ‗master‘, and the second is the IDE ‗slave‘
 Logical partitions are numbered from 5
 Primary partitions are numbered from 1–4
 The devices /dev/hda, etc., refer to whole hard disks, not partitions
 Add the partition number to refer to a specific partition
 For example, /dev/hda1 is the first partition on the first IDE disk
 SCSI disks are named /dev/sda, /dev/sdb, etc
3 Using fdisk
 The fdisk command is used to create, delete and change the partitions on a disk
 Give fdisk the name of the disk to edit, for example: # fdisk /dev/hda
 fdisk reads one-letter commands from the user
 Type m to get a list of commands
 Use p to show what partitions currently exist
 Use w to quit and write the changes
 Use q to quit without altering anything
 Use with caution and triple-check what you‘re doing!
4 Making New Partitions
 Create new partitions with the n command
 Choose whether to make a primary, extended or logical partition
 Choose which number to assign it
 fdisk asks where to put the start and end of the partition
 SJAHER,MOOLAMATTOM
The default values make the partition as big as possible Sigma Sathyan
77

 The desired size can be specified in megabytes, e.g., +250M


 Changes to the partition table are only written when the w command is given
5 Changing Partition Types
 Each partition has a type code, which is a number
 The fdisk command with option -l shows a list of current partition tables along with the hard
drives attached to the workstation or server.
 The command t changes the type of an existing partition
 Enter the type code at the prompt
 Linux partitions are usually of type ‗Linux native‘ (type 83)
 Other operating
6 Making Filesystems
systemsmight
with use
mkfsother types of partition, many of which can be understood

 by Linux
The mkfs command initializes a file system on a new partition
 Warning: any old data on the partition will be lost
 For example, to make an ext2 filesystem on /dev/hda2: # mkfs -t ext2 -c /dev/hda2
 -t sets the file system type to make, and -c checks for bad blocks on the disk
 Working
mkfs useswith
otherpartitions
programsin
to Linux
make specific types of file system, such as mke2fs and mkdosfs
The fdisk command with the option –l qualifier display the current partition tables along with
the Hard Drives to the workstation/server as :
$ fdisk –l
Once we have determined which hard drive to partition, we can run the fdisk command
followed by the hard drive. Here we will use the first hard drive (sda).
$ fdisk /dev/sda
Once fdisk command is executed, our command prompt will change to ―Command (m for
help):‖ and we will be ready to examine and partition the hard drive. The commands which
are supported by fdisk can be displayed by pressing the ―m‖ character followed by the Enter
key. The commands which will be used are ―p‖ for printing the partition table, ―n‖ for
creating a newthe
Displaying partition
currentandpartition
―w‖ fortable
saving the changes and exiting.

The first step before partitioning the hard drive is to get the disk space availability and what
the current partition table looks like. The character used with the fdisk is the ―p‖ which print
current partition table.
Creating a new partition

The next phase is to create the new partition. For example, we will create a partition of type

SJAHER,MOOLAMATTOM Sigma Sathyan


78

―Linux‖ with the partition size of 1 GB. The command to create a new partition is the ―n
character, we will enter what cylinder to star from (User should select the Default) and the
size of the partition.
Writing the new partitions to disk
Now we have the newly created partition and we save the changes by issuing the ―w‖
character which write the new partition table to hard disk as
Activating the new partition
After the new partition table ahs been written to the hard disk, Kernel can read the new
partition without rebooting. The first step is to create a mount point for the new partition. Here
we will use ―/media/newpartition‖ and the command ―partprobe‖ to have the kernel read the
partition table –
LINUX:~ # mkdir/media/newpartition

LINUX:~ # partprobe
Now we can format the partition and place a file system of our choice on it, (EXT2, EXT3,
REISERFS). Suppose we have chosen the RESIERFS file system –
LINUX:~ # mkfs.reiserfs /dev/sda6
Once we have the partition properly formatted with the file system, now we can mount and
use the newly created partition as LINUX:~ # mount /dev/sda6/media/newpartition
LOGIN TO LINUX
Linux never allows anybody to enter without user name and password. For example:
login:arjun
password:
Linux doesn‘t show your password, not even Asterisks (*) when we type it. It is for safety.

CHANGING YOUR PASSWORD


We can change our password with the passwd command. It first asks to type the old
password, and then asks for a new one. Linux direct the user to type the password twice when
we change it.
$ passwd
Changing password for arjun

Old password:
New password
Retype new password:
SJAHER,MOOLAMATTOM Sigma Sathyan
79

$
If the two passwords we type don‘t match, the password remains unchanged. This is due to
safety precaution – if we made a mistake typing the new password and Linux only asked you
once , then our password may be changed to some new value and we will have no way of
knowing that password.
$ passwd arjun  this command will change arjun‘s password

$ passwd –d arjun  this command will delete arjun‘s password

LOGIN AS SUPER USER /ROOT


Root is the administrator or Super User in Linux. And Super User can perform any activity in
Linux. To login as root /super user , enter the su command .
$ su
Password:
After entering the valid password of root, we will be logged in as root or Super User. After
this we will be able to perform any action on Linux OS.
root #
You can also use su to become any user on the system, not just root. For example, to become
kumar, you would enter this command:
# su -kumar
Don‘t forget to use the minus sign when you use su to temporarily become another user.

Getting system information with uname and hostname command.

hostname : displays and set system host name

Examples :
a) To display the host name
[mca@chavara amitha]$ hostname

chavara.santhigiri.net
b) Display the IP address of the system

[mca@chavara amitha]$ hostname -i

c) Set the hostname of the system to MGU


172.25.0.15
[mca@chavara amitha]$ hostname MGU

SJAHER,MOOLAMATTOM Sigma Sathyan


80

hostname: you must be root to change the host name

uname - print system information(OS information)


Syntax : uname [OPTION]...
DESCRIPTION : Print certain system information. With no OPTION, same as -s.
-a, --all
print all (basic) information, currently available from the system:

-s, --kernel-name

print the kernel name

-n, --nodename
print the network node hostname(it is the name by which system is known to the
network)
-r, --kernel-release

print the kernel release

-v, --kernel-version
[mca@chavara amitha]$ uname

Linux
[mca@chavara amitha]$ uname -p

i686
[mca@chavara amitha]$ uname -a
Linux chavara.santhigiri.net 2.6.9-42.0.0.0.1.ELsmp #1 SMP Sun Oct 15 14:02:40 PDT 2006
i686 i686 i386 GNU/Linux

Installing and removing packages with rpm command


We can use the rpm command to mange and install software packages. The command name
stands for the Red Hat Packet Manager. It is this command that performs installation, removal
and verification of software packages.
Each software Package is actually an RPM package, consisting of an archive of software files
and information about how to install those files. Each archive resides as a single file with a
name that ends with .rpm , indicating it is a software package that can be installed by the Red
Hat Package Manager.
Use rpm command either to install or uninstall a package with various options.
SJAHER,MOOLAMATTOM Sigma Sathyan
81
Syntax: rpm – options package_name

Options & their meaning


-U update package, same as install but any previous version is removed.

-I Install package
-e Remove package
-qi Display information for an installed package

-ql Display the list of files for an installed package


-qpi Display information from an RPM package file. (Used for uninstalled package)

-qpl Display file list from an RPM package file.(Used for an uninstalled package)

Examples:
$ rpm –Uvh mozilla -1.orc3 -0.1386.rpm

It installs & upgrades the above package.

$ rpm –qpl Webmin – 0.980 – 1.noarch.rpm

Here –qpl lists the files in the Webmin package.

$ rpm
The –eremoves
user xtetris the xetris game from the system.

$ rpm –qi xv
Display information about the installed package.

$ rpm –ql xv
Display a listing of files a given RPM package contains.

Uninstall options to be used with –e


--test Tests uninstall. Doesn‘t remove only checks for what is to be removed.
--nodeps Uninstalls without checking for dependencies.
--allmatches Removes all versions of package.

Direct Installation from Internet


We can install the packages directly from Internet by giving its URL
$ rpm –i ftp://ftp.mguniversitynotes.com/Antivirus.rpm
SJAHER,MOOLAMATTOM Sigma Sathyan
82

This command uses anonymous FTP i.e., no username and password required. The URL
may also contain a username and password preceding the hostname.
$ rpm –i ftp://username:password@ftp.mguniversitynotes.com/Antivirus.rpm

But through this format anyone can see our password.


$ rpm –i ftp://smith@ftp.gnomovision.com/pub/rpms/apmd-2.4-1.i386.rpm

Password for smith@ ftp.gnomovision.com :mypass (not echoed)

After entering a valid password, RPM installs the package.


Dependencies before installing software packages.
Many software packages are dependant on other packages. This is known as software
installation dependency. In the same manner, many Linux packages need some other files or
programs to perform the installation.
Example:
We want to install a software MYSOFTWARE.RPM. Suppose this package can‘t be installed
without installing FLASHPLAYER.RPM. In this case MYSOFTWARE.RPM is dependent in
FLASHPLAYER .RPM.
# rpm –i MYSOFTWARE.rpm
Failed dependencies.FLASHPLAYER.RPM is needed by MYSOFTWARE.rpm

#
When we try to install the rpm package check the database for dependencies. If RPM do not
find those dependent files in the database, the installation will stop & display warnings of
Failed Dependencies.
When RPM shows a dependency error it displays a list of files that are required. We can
bypass the dependencies and install the software without installing those dependent programs.
We should use the --nodeps option to tell RPM not to check any dependencies before
installing the package.
# rpm –i MYSOFTWARE.rpm --nodeps
This command forces rpm utility to ignore dependency errors and install software anyway.
One point should be noted that if the needed files are missing anyway, the software will not
work well or not at all.
Password is stored in /etc/shadow file

The encrypted password of any user is not stored in /etc/passwd file. It is stored in the
/etc/shadow file. It is another method of storing user account information with the shadowpassword
format.
SJAHER,MOOLAMATTOM Sigma Sathyan
83

The ―/etc/shadow‖ file contains password as well as other information such as account or
password expiration values etc. It is readable only by the root account and is therefore less of
a security risk. Almost all Linux OS use shadow password suite, where /etc/passwd has
asterisks (*) instead of encrypted password.

The /etc/shadow file contains password and account expiration information for users. As with
passwd file, each filed in the shadow file is also separated with ― : ― . It contains fields like
username (up to 8 characters) password (13 characters encrypted), no: of days indicating
password last changed etc.

Temporary disabling of user‟s accounts.


(1) Due to security reasons sometimes it becomes necessary to temporarily disable an account,
without actually removing it. The best way to disable an account is to change its shell into a
special program that just prints a message. This way, whoever tries to long into the account,
will fail and will know why. The message should tell the user to contact the system
administrator
It so that
is also possible to any problems
change may be dealt
the username with. to something else, but then the user
or password
may not know the actual reason. Confused Users mean more work for the administrator.
A simple way to create the special programs is to write ‗tail scripts‘:

#! usr/bin/tail +2
This account has been closed due to security breach.

Please call 555 – 1234 and wait for the men in black to arrive.
The first two characters (#!) tell the kernel that the rest of the line is a command that needs to
be run to interpret this file. The tail command in this case outputs everything except the first
line to the standard output.
Example: If user Anuj is suspected of a security breach, the system administrator would do
something like this:
# chsh –s
/usr/local/lib/no-login/security anuj

# su – tester
This account has been closed due to a security breach.

Please call 555 – 1234 and wait for the men in black to arrive.

SJAHER,MOOLAMATTOM Sigma Sathyan


84

#
The purpose of su command is to test that the change worked. Tail scripts should be kept in a
separate directory, so that their names do not interfere with the normal user commands.

(2) To disable a user account, edit as root the ― /etc/shadow‖ file (assuming you are using
shadow passwords) if not edit the ― /etc/passwd ― file instead and replace the password (
which is stored in its encrypted form ) with a * character. All Unix passwords, regardless of
length (up to a minimum of 8 characters), are stored in the password file as encrypted strings
of 13 characters. Therefore by replacing the password with a single * character it is
impossible for the user to login. This method will require you to assign a new password to the
user if you re enable the account, since the encrypted password field will have been replaced.
One solution to this which seems to be popular among system administrators is to simplify
File Access Permissions FAP
prefix the * character in front of the encrypted password to disable the account, and simplify
FAP helpsthe
removing to*secure files
to enable it. and folders. File access permissions refer to the permissions
associated with a file or directory with the respect of the following:
 File Owner
 Group Owner
 The
Other Users
Permissions that can be granted or revoked are symbolically represented by the letters
r,w,x .
The Permissions for a file or a directory are:

Access Denoted by Action Permitted on The Action Permitted on The Directory


Type File
r Read Permission Allows you to display, Allows you to list the contents of the
copy and compile the file directory
w Write permission Allows you to edit, Allows you to create directories and
rename and move the file subdirectories with in this directory
to another location
x Execute Permission Allows you to execute the Allows you to move to the specified
file with read permission directory using the cd command

SJAHER,MOOLAMATTOM Sigma Sathyan


Viewing File Access Permissions 85

We can view the file access permissions by using the ls -l command.


example:
[steve@localhost ~]$ ls -l file1
-rw-rw-r-- 1 steve steve 52 Jun 20 15:14 file1
The above command displays the FAP of file1. We can view the file access permissions of all
files and directories in the current directory we can use ls -l command without a file or a
directory name.
Changing File Access Permissions
File Access permissions associated with the file or a directory can be changed by using the
chmod command. We can use chmod command to grant or revoke the file access permissions
for files or directories.
The Synatx for chmod command is shown below

chmod <mode><filename>
We can use 2 modes with the chmod command
1) Symbolic mode- The Permission and the user type are specified as symbols
2) Absolute Mode-The Permission is specified as numbers.
Absolute Mode- In this mode we are using a series of digits to represent the file access
permissions. The Following table explains the number that denotes each type of permissions:

Number Permission

4 Read

2 Write

Execute
1

To get the permission bits you want, by add up the numbers accordingly. For example, the
rwx permissions would be 4+2+1=7, rx would be 4+1=5, and rw would be 4+2=6. We are
assigning separate permissions for the owner, group, and others, so we need a three-digit
Example:
number representing the permissions of all these groups.
$ chmod 755 testfile
This would change the testfile's permissions to -rwxr-xr-x. The owner would have full read,
write, and execute permissions (7=4+2+1), the group would have read and execute
permissions (5=4+1), and the other users would have the read and execute permissions as
SJAHER,MOOLAMATTOM Sigma Sathyan
86

well.
$ chmod 640 testfile
In this case, testfile's permissions would be -rw-r-----. The owner would have read and write
permissions (6=4+2), the group would have read permissions only (4), and the others
access permissions (0).
wouldn't have any
Symbolic Mode
In symbolic mode we are using symbols to specify the permissions and the types of the users.
The Following table represents the symbolic notation for the users.

The symbolic mode uses an operator to specify how the modes of a file should be
adjusted. The
following operators are accepted:
+ granting a permission to a class of users

- Revoking Permission from a class of users

Example:
Assigning Execute Permission to the Owner
chmod u+x file1

chmod u-x file1 Revoking Execute Permission from the Owner

chmod u-x-w file1 Revoking Execute abd write Permission from the Owner

chmod a+x file1 Assigning Execute permission to all the users

SJAHER,MOOLAMATTOM Sigma Sathyan


87

<How to change a file's owner and group in Linux >

We can change the owner and group ownership of files and directories with the chown and
chgrp commands.
< CHOWN - CHANGE THE OWNER OF A FILE >
You can change the owner and group of a file or a directory with the chown command. You
can do this only if you are the root user or the owner of the file. Set the file's owner:
$ chown username somefile
After giving this command, the new owner of a file called somefile will be the user username.
The file's group owner will not change. Instead of a user name, you can also give the user's
numeric
You canID here
also set ifthe
you want.
file's group at the same time. If the user name is followed by a colon and
a group name, the file's group will be changed as well.
$ chown username:usergroup somefile
After giving this command, somefile's new owner would be user username and the group
usergroup.
You can set the owner of a directory exactly the same way you set the owner of a file:
$ chown username somedir
Note that after giving this command, only the owner of the directory will change. The owner
of the files inside of the directory won't change.
In order to set the ownership of a directory and all the files in that directory, you'll need the -R
option:
$ chown -R username somedir
Here, R stands for recursive because this command will recursively change the ownership of
directories and their contents. After issuing this example command, the user username will be
the$owner
chownof-vthe directorysomefile
username somedir, as well as every file in that directory. Tell what happens:
changed ownership of 'somefile' to username. Here, v stands for verbose. If you use the -v
option, chown will list what it did (or didn't do) to the file.
The verbose mode is especially useful if you change the ownership of several files at once.
For example, this could happen when you do it recursively:

$ chown -Rv username somedir


changed ownership of 'somedir/' to username
changed ownership of 'somedir/boringfile' to username
changed
As ownership
you can of 'somedir/somefile'
see, chown to username
nicely reports to you what it did to each file.

SJAHER,MOOLAMATTOM Sigma Sathyan


88

< CHGRP - CHANGE THE GROUP OWNERSHIP OF A FILE >

In addition to chown, you can also use the chgrp command to change the group of a file or a
directory. You must, again, be either the root user or the owner of the file in order to change
the group ownership.
chgrp works pretty much the same way as chown does, except it changes the file's user group
instead of the owner, of course.
$ chgrp usergroup somefile
After issuing this command, the file somefile will be owned by a user group usergroup.
Although the file's group has changed to usergroup, the file's owner will still be the same.
The options of using chgrp are the same as using chown. So, for example, the -R and -v
options will work with it just like they worked with chown:

$ chgrp -Rv usergroup somedir


changed group of 'somedir/' to usergroup
changed group of 'somedir/boringfile' to usergroup
changed group of 'somedir/somefile' to usergroup

SJAHER,MOOLAMATTOM Sigma Sathyan


89

UNIT 4 SHELL PROGRAMMING

Basics of shell programming.


A Shell Program or a Shell Script is a block of code which consists of shell commands. A
shell program may have a few commands or can be very complex in operation with thousands
of shell commands. It is written using a text editor like vi or joe editor. Shell Script is
analogous to a batch file in MSDOS but more powerful than the MSDOS batch file.
Features of shell program
 Shell program has the functionality of input/output, iteration, logical decision making,
file creation and deletion as well as operations of system calls.
 Shell program may consist of one or more shell commands
 It can be created using any text editor of choice – vi, joe, emacs etc
 It is format free. It means that blank lines, indentation and white spaces can be used.
 Own commands can be created using shell programming.
A shell program saves a lot of time.
 It helps in performing repeatedly occurring tasks.
Shell programs save a lot of time.
 It can be used for automate routine tasks.
 System Administration Part can be automated using shell script very efficiently which
may include creating deleting updating users profiles.

 Easy to write debugging code into a script to detect and fix bugs

When to use shell scripts
Shell programs can be used for a variety of tasks some of which are mentioned below:
 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.
 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.

program,Automating repetitive
linking it with tasks. For
some libraries example, the
and executing theexecutable
repetitive code
task can
of compiling
be assignedatoCa
shell script. Another example could be that of producing sales reports every month.
 Executing important system procedures like shutting down the system, formatting a
disk, creating a file system on it, mounting the file system, letting the users the floppy and
finally unmounting the disk.
 Performing same operation on many files. For example, you may want to replace a
string printf with a string myprintf in all the C programs present in the directory.

SJAHER,MOOLAMATTOM Sigma Sathyan


You shouldn‘t use shell programming when the task:
90

 Is too complex, such as writing an entire billing system.


 Requires a high degree of efficiency.
Requires a variety of software tools.

Writing and Executing the Shell Scripts
Following steps are required to write shell script:
1) Use any editor like vi, joe, emacs to write the script.
2) Save and exit the editor file. Press :wq
3) To executeorthe
bash scriptname shscript use any of these two steps:
scriptname
chmod u + x script_filename or chmod 755 script_filename and then apply
./script_filename
The character # is used as a comment.

echo command
Use echo to display text or value of variables.
Options used with echo:
-n do not output the trailing line
-e enable interpretation of the following backslash escaped characters in the strings:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n
\t new line
\r
\\ carriage return
Shell Keywords
horizontal tab
Keywords backslash
are the words whose meaning has already been explained to the shell. The
keywords cannot be used as variable names because if we do so we are trying to assign anew
meaning to the keyword, which is not allowed by the shell. The keywords are called Reserved
words. Given below are list keywords used in Bourne Shell:
echo, read, set, unset, readonly, shift, export, if, else, fi, while, do, done, for, until, case, esac,
break, continue, exit, return, trap, wait, eval, exec, ulimit, umask
Shell Variables
They are an integral part of shell programming. It provides the ability to store and manipulate
information within a shell program. The variables you use are completely under your control.
We can create and destroy any number of variables as needed to solve the problem at hand.
The rules for building shell variables are as follows:
SJAHER,MOOLAMATTOM Sigma Sathyan
91
A variable name is any combination of alphabets, digits and an underscore.

No commas or blanks are allowed within a variable name.

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

Variables names should be of any reasonable length.

Variable name are case sensitive. I.e., Name, NAME, name, Name are all different variables.

Eg: si_int
m_hra
pop_e_89

Way of Assigning Values to Variables.


We can assign values to shell variables using a simple assignment operator. Note that while
assigning values to variables using the assignment operator ‗ = ‗ , there should be no spaces
on either side of =. If you leave space the shell will try to interpret the value being assigned as
a command to be executed.
Variables are of two types:

System defined variables or Environment variables


These are standard variables which are always accessible. The shell provides the values for
these variables. They are used by system itself and govern the environment we work under.
The $ prompt that we see is the default linux defined variable PS1 standing for system
prompt1. We can assign anew value to PS1 other than $ as:
$ PS1=‖what next‖
what next
So now every time the system prompts you, it displays not the $ but what next.

Commonly used system defined variables:


Variable Meaning
PS2 The system prompt 2, default value is ―>‖
PATH Defines the path which the shell must search in order to execute any command or
file.
HOME stores the default working directory of the user. On entering just a cd, the system
understands that is where we want to go and we are back to our default directory.
LOGNAME Stores the login name of the user
MAIL
Defines the file along with the path where the mail of user is stored.
SJAHER,MOOLAMATTOM Sigma Sathyan
92

MAILCHECK Defines the duration after which the shell checks whether the user has
received any mail. By default its value is 600 seconds.
IFS Defines the Internal Field Separator, which is a space, a tab, or a new line.
SHELL Defines the name of your default working shell.

TERM Defines the name of the terminal on which you are working.

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


The list of all system variables and their values can be displayed by saying at the $ prompt,
$ set

HOME=/usr/veena

HZ=100
IFS
LOGNAME=veena

MAIL=/usr/spool/mail/veena

MAILCHECK=600

OPTIND=1
PATH=/bin:/usr/bin:/usr/veena:/bin:.

PS1=$
PS2=>
SHELL=/bin/sh

TERM=vt100
TZ=IST-5:30

User defined Variables


These are defined by users and are used most extensively in shell programming. The variable
length can be of any reasonable length and may constitute alphabets, digits, underscores. But
the first character must be an alphabet or an underscore.
Theabove
In the $ symbol is used
example thetovalue
referoftovariable2
the contents of a variable.
is assigned to variable1. The braces are used to
variable1=${varaible2}
delimit the variable name. For example, consider a variable named today that contains the
value 20 and another variable named x. You need to assign the value 20 th to variable x by
concatenating the value of the variable today with the string th. To concatenate the values,
you will use the command:

SJAHER,MOOLAMATTOM Sigma Sathyan


93

$ x=${today}th
Now, x would contain the value 20 th.
However the following command will not produce the desired result because the shell will
look for a variable named todayth:
$ x=$todayth
The braces are optional in case you are not concatenating variables. The following two
commands will have the same result:
$ x=$today
$ x=$ {today}
$ Variable
a=20 a is declared and assigned a value of 20. To display the value of variable use ‗echo‘
$ echo $a or $ echo ${a}

20
If we avoid $ simply the variable a will be displayed.
$ echo a
a$ b=12

$ echo $b
12
$ echo ― $b ‖
12
$ echo ‗ $b ‘
$b
Note:
$ echo ` $b `
All12
shell variables are string variables. In the statement a=20, the ‗20‘ stored in a is treated not
as number, but as a string of characters 2 and 0. We can not carry out arithmetic operations on
them unless we use a command called expr.
A variable may contain more than one word. In such cases the assignment must be made using
double quotes.
$ c=‖two words‖
$two
echo $c
words

SJAHER,MOOLAMATTOM Sigma Sathyan


We can carry out more than one assignment in a line. So also we can echo more than one
94
variable‘s value at a time.

$ name=johny age=10
$ echo $name $age
$ johny 10
We can also use:
$ echo Name of the boy is $name, and his age is $age.
Name of the boy is johny, and his age is 10.
All variables defined inside a shell script die at the moment the execution of the script is over.
A variable which has been defined but has not been given any value is known as null variable.
A null variable can be created in any of the following ways:
$ d=‖‖
$ d=‘‘
$ d=
On echoing a null variable , only a blank line appears on the screen.
$ a=‖‖
$ echo $a
$
If a null variable is used anywhere in a command the shell manages to ignore it. For example:
$ var1=‖‖
$ var2=‖‖
$ wc –l $var1 $var2 file1
Since the var1, var2 were null variables the shell promptly eliminated them from the
command line and displayed the number of lines present in the file1.
Not only the system variables but also the user defined variables defined at the $ prompt or in
a shell script can be displayed using set command.
Reading a value into a variable
Besides allowing you to assign a value to a variable, the shell lets you to specify a value for a
variable by using the keyboard. You can enter the value into a variable during the execution of
a shell script by using the read command.
$ read name
On execution the read command waits for you to enter a value for the variable. When you
press the <Enter> key after entering a value, the remaining part of the shell script, if any is
executed. The read command doesn‘t prompt you to enter data. But you can use echo
command to display a prompt.
SJAHER,MOOLAMATTOM Sigma Sathyan
$ echo ―enter your name ― 95

enter your name

Annu  press Enter

$ echo $name

Annu
Unchanging Variables
If we want that variable a ‗s value should always remain 20 and not changed, you can use:
$ a=20
$ readonly a
When the variables are made readonly the shell doesn‘t allow us to change their values. All
such variables can be listed by entering readonly the $ prompt.
Wiping Out Variables
Variables can be made to cease existing. If we want the shell to forget about a variable
altogether, we use the unset command.
$ unset b
On issuing such command will remove variable b and its values assigned are erased from
shell‘s memory. But we cannot issue:
$ unset PS1
Because if PS1 is unset then there will be no system prompt left for you to issue any
commands.
Exporting variables
By default any variable is available only in the shell in which it is defined. The following
sequence of commands shows this:
$ a=20

$ sh
$ echo $a
$ exit  exit from the child shelll

$ echo $a

20 defining a, we invoked a sub shell by using sh at the prompt. We can leave this sub shell
After
by saying exit or Ctrl d.
SJAHER,MOOLAMATTOM Sigma Sathyan
96

Since variable „a‟ was defined in its parent shell, it has no identity in child shell. But when we
leave the child shell we can make „a‟ alive. If we want variables to be available to all sub
shells we create we have to export them from the parent shell.
$ a=20

$ export a

$ echo $a

20
$ sh
$ echo $a

20
$ a=12

$ echo $a

12
Press ctrl d  displays exit and returns to parent shell

$ exit
$ echo $a
 parent shell continues to have the value 20
20
To obtain a list of all exported variables we use export at the shell prompt.
$ export

Note:
a) A variable once exported from the parent shell becomes available to the sub shell or any
other shells launched from this sub shell. This so happens because whenever a sub shell is
executed, the lists of exported variables get copied to the sub shell, while the local
(unexported) variables in parent shell does not.
b) Once a variable is exported it remains exported to all sub shells that are subsequently
executed.
c) We can first create the variable and then export it or first export it and then create it.
export a b c
a=100 b=200 c=300
is same as

a=100 b=200 c=300


97

export a b c
d) A variable once exported remains exported. If we are to unexport it we must first unset it
and then recreate it.
e) A variable can be exported from the parent shell to its sub shell, but reverse is not true.
Thus if we create a variable ‗b‘ in a sub shell and then export it, it would not become available
to the parent shell.
f) If the sub shell changes the value of exported variables the value of this variable in the
parent shell remains unchanged since the sub shell always works on the copy of the variable
in the parent shell.
g) If an exported variable is modified in a sub shell then to make this modified value available
to a sub shell once again export the variable in the sub shell.
Shell Programs
1) Program to display a hello message
$ vi pgm1
#!/bin/bash
echo ―hello how are you‖
:wq
$ chmod u+x pgm1
$ ./pgm1
OUTPUT
hello how are you

2) Program to print user information who currently login and calendar


$ vi user.sh
clear
echo ―user is : $USERNAME ―

echo ― Today is \c ―; date

echo ―number of user login : \c‖; who | wc –l

:wq
$ sh user.sh
98
OUTPUT
user is : arun
Today is Sat Feb4 20:09:43 EST 2012
number of user login : 4

Solving arithmetic expressions using expr command

The command expr is used to perform arithmetic operations. Its syntax is as follows:

$ expr number1 operator number2


Examples:
$ a=5
$ b=4
$ expr $a + $b
9
$ expr 5 / 2
2
$ var1=5
$ var1= ` expr $var1 + 20 `
$25echo ‗expr 5 + 3‘
expr 5 + 3
$ echo ― expr 5 + 3 ―
$ echo `expr 5 + 3 `
expr
8 5+3

If you assign a string to a variable then try to add 1 to it, you will not get the result:
$ x=‖hello‖
$ y=`expr $x + 1`
expr: non numeric argument
$

Arithmetic Expansion
To calculate the value of an expression you can enclose the expression in $ ( ( ….. ) )
Example:
$ echo $ ( ( 45 + 34 ) )
79
$ a=12
99

$ b=10
$ echo $ ( ( a + b ) )
22

Shell program to print the total number of unanswered queries in a BPO company
$ vi call.sh
echo ―Enter the total number of calls reported today : ―
read total
echo ―Enter total number of answered calls : ―
read ans
unanswered=$ ( ( total – ans ) )

echo ― number of unanswered calls : $unanswered ―

OUTPUT
$ sh call.sh
Enter the total number of calls reported today : 120

Enter total number of answered calls : 109

number of unanswered calls : 11

Script to read your name from keyboard & to display a message

$ vi mesg
#!/bin/bash
echo ―Your name please : ―

read fname
echo ―Hello $fname , We are friends‖

OUTPUT
$ chmod u+x mesg
$ ./mesg
Your name please : Amitha

Hello Amitha , We are friends

Exit status
By default in Linux if a particular command or script is executed it returns two types of values
100

which is used to show whether the command or script is successful or failure. This value is
called exit status. If the value returned is zero, command or script is successful. If the value
returned is non zero, command or script is failure. To print that value use $? with the echo
command.
Examples:
1)$ rm test
rm : cannot remove test: no such file or directory
$ echo $?
2

2)$ cat sample


1234
$ echo $?
0

More command on one command line

To run two command with one command line.

Syntax:
command1;command2
Examples:
Will print today's date followed by users who are currently login.
$ date;who

Wild cards (Filename Shorthand or meta Characters)

Wild card
Meaning Examples
/Shorthand
$ ls * will show all files

will show all files whose first name is starting


Matches any $ ls a*
string or with letter 'a'
*
group of $ ls *.c
will show all files having extension .c
characters.
will show all files having extension .c but file
$ ls ut*.c
name must begin with 'ut'.
101

will show all files whose names are 1 character


Matches any $ ls ?
long
? single
character. will show all files whose names are 3 character
$ ls fo?
long and file name begin with fo
Matches any

[...] one of the $ ls [abc]* will show all files beginning with letters a,b,c
enclosed
characters

Note:
[..-..] A pair of characters separated by a minus sign denotes a range.

Example:
$ ls /bin/[a-c]*

Will show all files name beginning with letter a,b or c like

/bin/arch /bin/awk /bin/bsh /bin/chmod /bin/cp


/bin/ash /bin/basename /bin/cat /bin/chown /bin/cpio
/bin/ash.static /bin/bash /bin/chgrp /bin/consolechars /bin/csh

But
$ ls /bin/[!a-o]
$ ls /bin/[^a-o]

If the first character following the [ is a ! or a ^ ,then any character not enclosed is matched
i.e. do not show us file name that beginning with a,b,c,e...o, like

/bin/ps /bin/rvi /bin/sleep /bin/touch /bin/view


/bin/pwd /bin/rview /bin/sort /bin/true /bin/wcomp
/bin/red
/bin/remadmin /bin/sayHello /bin/su/bin/stty/bin/uname
/bin/sed /bin/umount /bin/xconf
/bin/ypdomainname
/bin/rm /bin/setserial /bin/sync /bin/userconf /bin/zcat
/bin/rmdir /bin/sfxload /bin/tar /bin/usleep
/bin/rpm /bin/sh /bin/tcsh /bin/vi

Decision Making & Conditional Statements


If condition
102

The if condition is used in decision making in shell script. If the given condition is true, the
command is executed otherwise won‘t. Condition is the comparison between the values. For
example, you have seen in some websites, ―Enter only if you are 18+‖. If you click on Yes
you can enter into the website and if you click No you won‘t be allowed to enter the website.
The expression that will be used in shell scripting are:
1. ―-gt‖ = Greater than

2. ―-lt‖ = Less than

3. ―-eq‖ = Equals to

4. ―-ne‖ = Not equals to

3. ―-ge‖ = Greater than or Equals to

4. ―-le‖ = Less than or Equals to

Test command or [ expression ]


Test command or [ expression ] is used to see if an expression is true, and if it is true it
returns zero else it returns nonzero value.

Syntax

test <expression>

or

[ expression ]

The test command can carry out several types of tests. These are:

(a) Numerical tests

(b) String tests

(c) File tests


As the name suggests, numerical tests are used when comparisons between values of two
numbers is to be done. They allow us to compare two values to see whether they are equal to
each other, unequal, or whether one is greater than the other. The operators that can be used
for numerical test are shown below:
103

Operator Meaning

-gt greater than


-lt less than
-ge greater than or equal to
-le less than or equal to
-ne not equal to
-eq equal to

Numerical Test

In a company an employee is paid as under:

If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of
basic. If his salary is either equal to or above Rs. 1500. then HRA = Rs. 500 and DA = 98% of
basic salary. If the | employee's salary is input through the keyboard write a program to find
his gross salary.
Program:

echo” Enter basic salary”

read bs

if [ $bs –lt 1500 ]

then

hra=`echo $bs \* 10 / 100 | bc`

da=`echo $bs \* 90 / 100 | bc`

else

hra=500

da=`echo $bs \* 98 / 100 | bc`

fi
gs=`echo $bs + $hra + $da | bc`

echo “Gross salary = Rs $gs “


104
Output

Enter basic salary 1200


Gross salary = Rs 2400

Enter basic salary 2000

Gross salary = Rs 3960


Note that the if statement instead of explicitly mentioning the word test we have replaced
the condition within
[ ] which is allowed.

File Test
The test command has several options for checking the status of a file. These are shown
below. Using these we can find out whether the specified file is an ordinary file or a directory,
or whether it grants read, write or execute permissions, so on and so forth.
Option Meaning

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

True if the file exists and is not a directory


-f file
-d file True if the file exists 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 write permission to it
-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
Program:
echo ―enter file name:‖
read fname
if [ -f $fname ]
then
echo ―you entered a file name‖

else
echo ―what you entered is not a file name‖

fi
105

Let us write another program on similar lines. This one checks whether the user has write
permission to a file. If yes, it prompts the user to type a message which then gets appended to
the mentioned file.
echo “Enter file name”

read filename
if [ -w $filename ]

then
echo “Type matter to append. To stop type Ctrl D.”
cat » $filename
else
echo” No write permission.”
If the
fi user has a write permission to the filename supplied from the keyboard, the matter typed
by the user is read by the cat command and then using redirection operator (») gets appended
to the desired file. When the user hits Ctrl d the cat command comes to an end.
String Tests
Another set of tests that the test command can handle are the string tests. The checks that we
can carry out using these tests are shown below:

Condition Meaning

string 1 = string2 True if the strings are same


string 1 ! = string2 True if the strings are different
True if the length of string is greater than 0
-n string
-z string True if the length of the string is zero
string
True if the string is not a null string

Program:
str1="Good"
str2="Bad”
str3=
[ $str1 = $str2 ]
echo $?
106

[ $str1 ! = $str2 ]
echo $?
[ -n $str1 ]
echo $?
Output
1
0
0
Can you figure out what will output of the following program?
Program:
str1=‖good morning‖

str2=‖good bye‖

[ $str1 = $str2 ]

echo $?
OUTPUT
test: unknown operator morning
Since two word strings are being assigned to variables str1 and str2 we have taken care to
enclose the strings within a pair of double quotes. But the test failed. Look at error message
and you would be able to understand the reason: The test command went to work with [ good
morning = good bye]. Naturally, morning was treated as an operator, hence the error. If you
write the test as
[ ―$str1‖ shown below
= ―$str2‖ ] the error won‘t occur:

1) IF-THEN-FI STATEMENT:

The syntax for ―if‖ statement is:


if <condition>
then
<command1> if condition is true or if exit status is zero
…….
……..
fi
107
Let‘s just take a simple example of 18+ websites. The simple logic is, if you are 18 and
older,you are allowed to enter otherwise not.

echo "Enter your age:: c"


read age
if test $age -ge 18
then
echo "You are allowed to enter"

fi
If the user enters the age greater than or equals to 18 he/she will be prompted will the message
―You are allowed to enter‖ and If the user enter the number less than 18 the program will exit.
Let me show you the output.

2) IF-THEN-ELSE-FI STATEMENT:

Now, add the else statement to the if statement.

echo "Enter your age:: c"


read age
if test $age -ge 18
then
echo "You are allowed to enter"
else
echo "You are not allowed to enter"
Now, if you input the number less than 18 you will be prompted will the message ―You are
fi
not allowed to enter‖.

3) elif [else + if]


The format of elif is same as that of if. For example:
#!.bin/bash
echo ―Please enter your age : ―
108

read age
if [ ―$age‖ –lt 13 ] || [ ―$age‖ –ge 60 ];
then
echo ―Invalid choice‖
elif [―$age‖ –ge 13 ] || && [ ―age‖ –lt 19 ];
then
echo ―Teenager‖
echo ―Youth of the nation‖
elif [ ―$age‖ –ge 20 ] && [ ―$age‖ –lt 25 ];
fi
then
4) Nested if-else-fi Statement
We can 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. Syntax is as follows:
then
if condition
if condition
then
…..
…..
else
…..
do this
fi
else
…..
do this
fi
Example:
choice=0
echo ―1. Ubuntu Linux‖
echo ―2. Suse Linux‖
echo –n ―Select the choice [1 0r 2]?‖
read choice
if [ $choice –eq 2 ]; then
if [ $choice –eq―you
echo 1 ]; then
pick up Suse Linux‖
echo ―you
else pick Ubuntu Linux‖
else #### nested
fi echo if-elses choice‖
―Invalid ie, if within if ###
fi
109

MULTILEVEL IF..THEN…ELSE STATEMENT:


IF YOU HAVE TO WORK ON MORE THAN TWO CONDITIONS YOU WILL USE NESTED IF ELSE STATEMENT.
HERE’S THE SIMPLE SCRIPT THAT YOU WILL MAKE YOU FAMILIAR WITH MULTILEVEL IF ..ELSE

STATEMENT.
#!/bin/sh
echo "Enter the age of your child: c"
read age
if test $age -le 1

then
echo "Use mother's milk"
elif test $age -le 5
then
echo "Baby is growing up"
elif test $age -le 10
then
echo "Really grown up"
else
echo "**Age should be less than or equals to ten only**"
fi
This is a simple script. See the output below.
110
case statement

The case statement is a good alternative to multilevel if-then-else-fi statement. It enables you
to match several values against one variable. Syntax is as follows:

case $variable_name in
option 1) command
…..
…..
command;;
option 2) command
…..
…..
command;;
option N) command
…..
…..
command;;
*) command
…..
…..
esac command;;

The $variable_name is compared against the patterns until a match is found. The shell then
executes all the statements up to the two semicolons that are next to each other. The default is
*) and it is executed if no match is found.
Example:
echo ―enter a number from 1 to 3 : ―
case $num in
read
1)num echo ―you entered 1‖
;;
echo ―you entered 2‖
2)
;;
echo ―you entered 3‖
3)
;; *) echo ― I said 1 to 3 !‖
;;
esac
111
LOOPS (Iteration Constructs in Linux)

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 which we can repeat
a part
a) of a using
program.
a forThey are:
statement
b) using while statement
c) using until statement
The for loop
Syntax:

for { variable name } in { list }

do

execute one for each item in the list until the list is

not finished (And repeat all statement between do and done)

done

Before try to understand above syntax try the following script:


$ cat > testfor
for i in 1 2 3 4 5
do
echo "Welcome $i times"
Run it above script as follows:
done
$ chmod +x testfor
$ ./testfor
The for loop first creates i variable and assigned a number to i from the list of number from 1
to 5, The shell execute echo statement for each assignment of i. (This is usually know as
iteration) This process will continue until all the items in the list were not finished, because of
this it will repeat 5 echo statements.
Syntax:
112
Even you can use following syntax:

for (( expr1; expr2; expr3 ))

do

..... ...

repeat all statements between do and

done until expr2 is TRUE

done

In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to
initialize variables for the loop. All the statements between do and done is executed repeatedly
UNTIL the value of expr2 is TRUE. AFTER each iteration of the loop, expr3 is evaluated.
This is usually used to increment a loop counter.
$ cat > for2
for (( i = 0 ; i <= 5; i++ ))
do
echo "Welcome $i times"
done
Run the above script as follows:
$ chmod +x for2
$ ./for2
Welcome 4 times
Welcome 0 times
Welcome 5 times
Welcome 1 times
In above example, first expression (i = 0), is used to set the value variable i to zero. Second
Welcome 2 times
expression is condition i.e. all statements between do and done executed as long as expression
Welcome 3 times
2 (i.e continue as long as the value of variable i is less than or equal to 5) is TRUE. Last
The while loop
expression
Syntax: i++ increments the value of i by 1 i.e. it's equivalent to i = i + 1 statement.
while < condition>
do
< commands s >
done
113

In the while construct, the commands to be executed are specified within the do and done
keywords. The do and done are used to delimit commands in an iteration construct. The
commands within the do and done keywords are executed as long as the condition evaluates to
true.
Example:
count=1
while [ $count –le 3 ]
do
echo ― enter values for p, n, r : ―
read p n r
si=‘echo $p \* $n \* $r / 100 | bc‘
echo ―simple interest = Rs $si ―
Conditional
count=‘exprwhile
$countloop
+ 1‘exit with break statement
You can do early exit with the break statement inside the while loop. You can exit from
done
within a WHILE using break. General break statement inside the while loop is as follows:

while [ condition ]
do
statements1 #Executed as long as condition is true and/or, up to a disaster-condition if
any.
statements2
if (disaster-condition)
then
break #Abandon the while lopp.

fi
statements3 #While good and, no disaster-condition.
done

In this example, the break statement will skip the while loop when user enters -1, otherwise it
will keep adding two numbers:

#!/bin/bash

while :
do
read -p "Enter two numnbers ( - 1 to quit ) : " a b
114

if [ $a -eq -1 ]
then
break
fi
ans=$(( a + b ))

done echo $ans

Early continuation with the continue statement


To resume the next iteration of the enclosing WHILE loop use the continue statement as
follows:

while [ condition ]
do
statements1 #Executed as long as condition is true and/or, up to a disaster-condition if
any.
statements2
if (condition)
then
continue #Go to next iteration of I in the loop and skip statements3
fi
done
statements3

You can use : special command with while loop to tests or set an infinite loop or an endless
loop. An infinite loop occurs when the condition will never be met, due to some inherent
characteristic of the loop. There are a few situations when this is desired behavior. For
example, the menu driven program typically continues till user selects to exit his or her main
menu (loop). To set an infinite while loop use:
1. true command - do nothing, successfully (always returns exit code 0)
2. false command - do nothing, unsuccessfully (always returns exit code 1)
3. : command - no effect; the command does nothing (always returns exit code 0)
Syntax

Use : command to set an infinite loop:

#!/bin/bash
# Recommend syntax for setting an infinite while loop
while : 115

do
echo "Do something; hit [CTRL+C] to stop!"
done
Use the true command to set an infinite loop:

#!/bin/bash
while true
do

echo "Do something; hit [CTRL+C] to stop!"


done
Use the false command to set an infinite loop:
#!/bin/bash
while false
do
echo "Do something; hit [CTRL+C] to stop!"

done
Note the first syntax is recommended as : is part of shell itself i.e. : is a shell built-in
command.
The until loop

Just like while loop, until loop is also based on a condition.

SYNTAX
The until loop continues running commands as long as the item in list continues to evaluate
true. Once an item evaluates false, the loop is exited. The syntax is:
until [ condition ]
do
command1
command2
...commandN
done
....
116

The while loop vs the until loop

1. The until loop executes until a nonzero status is returned.


2. The while command executes until a zero status is returned.
3. The until loop always executes at least once.
Example
Create a shell script called until.sh:
#!/bin/bash
i=1
until [ $i -gt 6 ]
do
echo "Welcome $i times."
i=$(( i+1 ))
Save and close the file. Run it as follows:
done
chmod +x until.sh
./until.sh
Sample outputs:

Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.
Welcome 5 times.
Welcome
The loop in 6thetimes.
above example initializes the variable i to 1, and then increments and displays
out the message until it equals 6.

Functions

When program gets complex we need to use divide and conquer technique. It means whenever
programs get complicated, we divide it into small chunks/entities which are known
as function.
Function is series of instruction/commands. Function performs particular activity in shell i.e.
it had specific work to do or simply say task.
Why to write function?
117
1)Saves lot of time.
2)Avoids rewriting of same code again and again
3)Program is easier to write.
4)Program maintains is very easy.

To define function use following syntax:


Syntax:function-name ( )
{
command1
command2
.....
...
commandN
return
Where function-name is name of you function that executes series of commands. A return
} will terminate the function. Example:
statement
Type SayHello() at $ prompt as follows
{$ SayHello()
echo "Hello $LOGNAME, Have nice computing"
return
}
To execute this SayHello() function just type it name as follows:
Hello vivek, Have nice computing.
$ SayHello
This way you can call function. Note that after restarting your computer you will loss this
SayHello() function, since its created for current session only.

Passing parameter to User defined function

You can pass the parameter i.e. command line option to function as you passed to shell script.
As you know you can define the function as follows:

function function-name( )
{
statement1
statement2

} statementN
.

118
119
if [ ―$1‖
And you –gt 1this
can call ]; function
then (without command line option) within the shell script as
follows:
Next=`expr $1 – 1`
function-name
Rec=`fac $next`
Prod=`expr
You can pass the$1 \* $Rec`to function i.e. command line option to function as follows:
parameter
echo $Prod
function-name arg1 arg2 arg3 argN
else
fi
To
} clear you1 idea lets write shell script:
echo
echo ―enter a number :‖
$ vi pass
read
echo num
―$num!= `fac $num`‖
function demo()
{
How
echo to de-bug"Allthe shell script?
Arguments to function demo(): $*"
While programming shell sometimes you need to find the errors (bugs) in shell script and
echo "First argument $1"
correct the errors (remove errors - debug). For this purpose you can use -v and -x option with
echo "Second argument $2"
sh or bash command to debug the shell script. General syntax is as follows:
echo "Third argument $3"
sh
Syntax: option { shell-script-name }
return
#
OR
}# optionCall { the shell-script-name function}
bash can
# be
Option shell input lines as are
demo -f foo bar they read.
-x Run
After expanding
the each simple-command,
above bash displays thescript
shell expanded value as of PS4 system
follows:
-v Print
variable,
$ followed by the commandchmod and its expanded arguments.+x pass
Example:
$All ./pass
$ Arguments to
cat function demo():
> -f foo dsh1.sh
First argument -f
bar
#
Second Script to show
argument debug of foo
shell
#Third argument bar
As #you can see the demo() function is$1
define at the beginning of shell
+ script. As you refer the$2`
command line args/option for shell script, same way you can refer the parameter for function.
tot=`expr ctrl
To Press
pass the parameter +
demo to functiond
-f we towrite itsave, and
as followsrunin shellitscript:bar
statement foo as
echo $tot chmod 755
This$ statement passes three parameter to function demo -f, foo and bar. All of these dsh1.sh
./dsh1.sh 4
$9
parameters are stored to $1, $2, and $3 variable of function demo(). 5

We$can write recursivesh functions in a shell


-x script. dsh1.sh 4 5
#
Consider
# the factorial:
Script to show debug of shell
#
vi fact.sh
tot=`expr $1 + $2`
fac ()
expr $1 + $2
{ Santhigiri College Sebsatian Cyriac
120

++ expr 4 + 5
+ tot=9
$tot
echo echo
9 + 9

See the above output, -x shows the exact values of variables (or statements are shown on
screen with values).
Use
$ sh -v -v option4to5 debug complex shell script.
dsh1.sh

Positional Parameters
Special built-in environmental variables are positional parameters which hold command-line
arguments to positions with the names 1,2,3,4, etc. which are indicated by $1,$2,$3,$4, etc.
Argument $0 is the name of the script. These parameters are named positional because
within the script the reference is to the position they occur on the command line.
These positional variables can be used by a script. Those used typically are variables $0-$9
and $#. Once you have created a script and you name and execute the script you can begin
using these positional parameters. For a script named param.sh, when you call the script you
can follow the script name with variables. Here is an example:
sh param.sh server mail
In this example the script is called param.sh so that is the first parameter ―$0‖ which is
automatically used. Then the next 9 parameters can be entered on the command line. Here
the first parameter is ―server‖ ―$1‖ and the second parameter is ―mail‖ ―$2‖.
sh param.sh server mail
Call with 2 parameters
The Shell Script Name is param.sh
$# number of parameters
The
$0 first parameter
script nameis server
$1-9second
The parameters
parameterbyisposition
mail entered
$@ thirdlist
The all parameters
parameter is used (places arguments on separate lines)
$*
All list all parameters
parameters
#!/bin/bash are serverused
mail(places arguments on one line separated by spaces)
Here
echois“Call
the actual
with script and a list of how to use the parameters.
$# parameters”
echo “The Shell Script Name is $0″
echo “The first parameter is $1″
echo “The second parameter is $2″
echo “The third parameter is $3″
echo “All parameters are $@”
121

The parameters that you enter are picked up and used by the script; these can vary every time
you use the script. So if you create the script the output of these two examples will each be
different because the positional parameters are different.
sh param.sh wokstation tech research
sh param.sh server web apache
You can use the built in command set to assign values of the arguments for the positional
parameters. The set command is a built in command that can be used with ―-o‖ to turn a bash
feature on and ―+o‖ to turn a feature off. At times the set command can be used inside a script
to assign values to variables. Here is a simple script that illustrates the point. Here called with
no parameters and called with one parameter the output is the same because they have been
assigned values.
Sciptname param2.sh
#!/bin/bash
setnetwork
server ipipnetwork
server
echo $3 $2
These $1
positional parameters are very useful when using them in scripts.
sh param2.sh
network ipParameters
Positional server
sh param2.sh
They 2 variables defined by the shell. They are nine in number named $1 through
are special
$9.Setting Values of Positional Parameters
To assign values to the positional parameters – use the set command.
$ set Friends come and go, but enemies accumulate
The above command sets the value $1 with 'Friends', $2 with 'come' and so on. To
verify, we use the echo statement to display their values.
Friends come and go, but enemies accumulate
On$giving
echo $1 $2 $3set
another $4command,
$5 $6 $7 the old values of $1, $2, etc are discarded and the new values

get collected.
$ set Do you want credit or results
$ set A smiling face is always beautiful
$ echo $1 $2 $3 $4 $5 $6
A smiling face is always beautiful
Had we echoed the values of $l through $6 before issuing the second set command obviously
the results would have been different.
Let us now see another way of setting values in positional parameters. Suppose we have typed
the line 'Give luck a little time and it will surely change' in a file called 'lucky'. We can make
122

set take the values to be assigned to positional parameters from this file by saying,
$ set `cat lucky`
$ echo $1 $2 $3 $4 $5
Give luck a little time
Whenever the quoting metacharcter `` are used the command given within `` is replaced by
the output of the command. In our case `cat lucky` got replaced by Give luck a little time and
it will surely change. Hence set used this sentence to set up the positional parameters as the
output of the echo command would justify. The characters `` are called reverse quotes or
more correctly ―accent graves‖.
Displaying Date in Desired Format
The date command by default displays the current date and time in the following format:
Fri Apr 19 11:30:45 IST 1996
To display the information in any order like:
Fri 19 Apr 1996
We can use the set command as follows:
$ vi pos.sh
set `date`
echo $1 $3 $2 $6
:wq
$sh pos.sh
Output
Fri 19 Apr 1996
Using Shift on Positional Parameters
We have used the set command to set up to 9 words. But we can use it for more.
$ echo
$ set You $1 $2 the
have $3 $4 $5 $6 $7
capacity to $8 $9 from mistakes. You will learn a lot in your life.
learn
mistakes.
$echo You$4will
$1 $2 $3 learn
$5 $6 $7 a$8
lot$9in$10
your$11
life.
Now where have the first seven words gone? They have been shifted out. Each word vacated a
You have the capacity to learn from mistakes. You You0 You1
position for the one on its right with the first word getting lost in the bargain. This occurred 7
Observe the last two words in the output. These occurred in the output because at a time we
times; hence we find the last 9 words in $1 through $9. The first seven are lost forever, as we
can access only 9 positional parameters. When we tried to refer to $10 it was interpreted by
did not take the precaution to store them elsewhere. To prevent the loss we should have done:
the shell as if you wanted to output the value of $1 and a 0. Hence we got YouO in the output.
$ set You have the capacity to learn from mistakes. You will learn a lot in your life.
$ b=$2
Same is the story with $11. It doesn‘t mean that words following the ninth word have been
$ a=$1
lost. They are safe with the shell. But to reach them we must do the following.
$ shift 7
123

$ c=$3
$ d=$4
$ e=$5
$ f=$6
$ g=$7
$ echo $a $b $c $d $e $f $g $1 $2 $3 $4 $5 $6 $7 $8 $9
$ shift 4
You have the capacity to learn from mistakes. You will learn a lot in your life.
We can employ an easier method.
$ set You have the capacity to learn from mistakes. You will learn a lot in your life.
$echo $*
You have the capacity to learn from mistakes. You will learn a lot in your life.
Here $* stands for all positional parameters, including those beyond $9. This means that
using $* we can access all the parameters taken together but not individually. The
following example would further clarify this concept.
$ vi pos2.sh
set If you are headed in the wrong direction, God allows U turns.
echo $*
shift 1
echo $*
shift 1
echo $*
echo $*
And here is the output you would get when you execute it...
shift 1
If you are headed in the wrong direction, God allows U turns.
echo $*
you are headed in the wrong direction, God allows U turns.
shift
are headed In the wrong direction, God allows U turns.
headed in the wrong direction, God allows U turns.
Observe
in thethe last direction,
wrong shift command in the program.
God allows U turns. Here we have not mentioned the number of
parameters to be shifted. When we do not do so, by default 1 parameter is shifted.
UNIT V
124
Simple Filter Commands – pr, head, tail, cut, sort, uniq, tr

Filters
A filter is programs that takes input from the standard input file, process it and sends the
output to the standard output file. Linux provides various filters like cat, grep, wc, tr cut etc to
enable you to work effectively with data
Filters Purpose
cat Concatenates and displays files
pg Paginates display for terminals
more
Displays a file one screenful at a time
head
Prints the first few lines of a file
tail
Displays the last few lines of a file
grep Sorts and merges files
Searches
Adds linefiles for a to
numbers pattern
a file
sort
pr Prints files to the standard output
nl
wc Counts lines, words and characters
tee
Creates a tee in a pipe
uniq Reports repeated lines in a file
tr Translates characters in a file
cut
Cuts out selected fields of each line of a file
paste
Mergesrequests
Sends lines oftofiles
line printer
lpr

tr - translate or delete characters. Translate, squeeze, and/or delete characters from standard
input, writing to standard output. Note that this command gets input from the standard input
(keyboard), not from a file. But you can use pipe or redirection to use a file as input.
tr <Character_Set1><Character_Set2><StandardInput>
[mca@chavara amitha]$ cat >e2.txt
computer
zoology
commerce
botany
physics
[mca@chavara amitha]$ cat e2.txt | tr "[a-z]" "[A-Z]"

SJAHER,MOOLAMATTOM SIGMA SATHYAN


125

COMPUTER

ZOOLOGY

COMMERCE

BOTANY
PHYSICS
[mca@chavara amitha]$ tr "c,o" "C,O" < e2.txt
COmputer

zOOlOgy

COmmerCe

bOtany
physics
The tr command used with –d option deletes the characters specified in <character_set> from
input, doesn‘t translate.
[mca@chavara amitha]$ tr -d "c,o" < e2.txt
mputer

zlgy
mmere

btany
physis
uniq
It is used to handle duplicate lines in a file. If this command is used without any option, it
displays the lines by eliminating duplicates lines.
Syntax:
$ uniq –options filename
Options used are:
-u displays only the non repeated lines
-d displays only the duplicated lines
-c displays each line by eliminating duplicate lines and prefixing the number of times it
occurs.
2 bb
Examples:
2 bb
$ cat emp
SJAHER,MOOLAMATTOM SIGMA SATHYAN

1 aa
126

3 cc
4 dd
4 dd
4 dd
5 ee
6 ff
6 ff
$ uniq emp
1 aa
2 bb
3 cc
4 dd
5 ee
6 ff
$$ uniq
uniq –d
–u emp
emp
21 bb
aa
43 dd
cc
65 ff
ee
$ uniq –c emp
1 1 aa
2 2 bb
1 3 cc
2 6 ff
3 4 dd
Refer notes of unit 1, 2 for commands : head tail cut sort pr
1 5 ee
Filters Using Regular Expressions: grep, egrep, sed
In the simplest terms, grep (global regular expression print) is a small family of commands
that search input files for a search string, and print the lines that match it. Although this may
not seem like a terribly useful command at first, grep is considered one of the most useful
commands in any Unix system. Grep is made up of three separate, yet connected commands,
grep, egrep, and fgrep, a sort of holy trinity of Unix commands. All three of the grep
commands work the same way. Beginning at the first line in the file, grep copies a line into a
buffer, compares it against the search string, and if the comparison passes, prints the line to
the screen. Grep will repeat this process until the file runs out of lines. Notice that nowhere in
SJAHER,MOOLAMATTOM SIGMA SATHYAN
this process does grep store lines, change lines, or search only a part of a line.
127

grep is an acronym for ‗globally search a regular expression and print it‘. The command
searches the specified input fully (globally) for a match with the supplied pattern and displays
it. While forming the patterns to be searched we can use shell meta charters or regular
expressions like ‗‘ ? [ ] !
The most useful grep flags are shown here:

Options Meaning
-i Ignore uppercase and lowercase when comparing.
-v Print only lines that do not match the pattern.
-c Print only a count of the matching lines.
-n Display the line number before each matching line.
-l Prints only the filenames of files in the query that have lines that match the search
string.
-w Checks if the given pattern is a word by itself and not a part of another word.

-r Checks for the given pattern, recursively within the directory that you specify after
the –r option.

When grep performs its pattern matching, it expects you to provide a regular expression for
the pattern. Regular expressions can be very simple or quite complex, so we won't get into a
lot of details here. Here are the most common types of regular expressions:
Regular Expression Meaning
abc Match lines containing the string "abc" anywhere.
^abc Match lines starting with "abc."
abc$ Match lines ending with "abc.

SJAHER,MOOLAMATTOM SIGMA SATHYAN


128

a..c Match lines containing "a" and "c" separated by any two characters
(the dot matches any single character).
a.*c Match lines containing "a" and "c" separated by any number of
characters (the dot- asterisk means match zero or more characters)

Examples:

1) To search the word picture in newsfile: $ grep picture newsfile

2) To search the word picture in two files $ grep picture file1 file2

3) For a search pattern consisting more than one word, single quotes can be used to enclose it

$ grep ‗the picture taken –i –n file1 file2


4) To search all occurrences of ‗Rebecca‘ as well as ‗rebecca‘ in myfile and display the lines
which contain one of these words. $ grep [Rr]ebecca myfile

5) To display all four letter words whose first letter is ‗b‘ and last letter ‗k‘. The two ??
symbols denotes one character each. Thus lines containing words like book, back, beak etc
will be listed. $ grep b??k myfile
6) To display all lines that do not contains words starting with ‗a‘. $ grep –v a* myfile

DOT [.] AS A SPECIAL CHARACTER

A dot [.] is an important special character. It matches everything except the newline character.
Example:

$ grep '^.8' telephone.txt or

$ egrep '^.8' telephone.txt

This searches for lines with 8 at the second position and anything as the first character.

Sets can also be inverted by starting the set description with "[^" rather than "[".

The combination of "[" "^" indicates the inverted set.


[0-9] Is a single character pattern that matches digit in the ascii range from zero to nine.
[^0-9] Match any single NON-digit character.

SJAHER,MOOLAMATTOM SIGMA SATHYAN


129

[^abc] Match any single character that is not a, b or c.

The dot matches everything except new line. It is the same as [^\n]. Where \n is the newline
character.
To match all lines that DO NOT START with a 1 we write -

grep '^[^l]' telephone.txt

or
egrep ‗^[^1]' telephone.txt

Regular expressions also come into play when using vi, sed, awk, and other Unix commands.
If you want to master Unix, take time to understand regular expressions. Here is a sample
poem.txtfile and some grep commands to demonstrate regular-expression pattern matching:
Mary had a little lamb
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print all lines containing ‘spam’ (respecting uppercase and lowercase), enter
grep 'spam' poem.txt
Mary fried a lot of spam
Jill had a lamb spamwich
To print all lines containing ‘spam’ (ignoring uppercase and lowercase), enter
grep -i 'spam' poem.txt
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print just the number of lines containing the word ‘spam’(ignoring uppercase and
lowercase), enter
grep –i -c 'spam' poem.txt
3
To print all lines not containing ‘spam’(ignoring uppercase and lowercase), enter
grep -i -v 'spam' poem.txt
Mary hadall
To print a little
lines lamb
starting with ‘Mary’, enter
grep '^Mary' poem.txt

SJAHER,MOOLAMATTOM SIGMA SATHYAN


To print all lines starting with ‘Mary’, enter 130
grep '^Mary' poem.txt
Mary fried a lot of spam

Mary
To hadalla lines
print little lamb
ending with ‘ich’, enter
grep 'ich$' poem.txt
Jack ate a Spam sandwich
Jill had a lamb spamwich
To print all lines containing ‘had’ followed by’ lamb’, enter
grep 'had.*lamb' poem.txt
Mary
Jill hadhad a little
a lamb lamb
spamwich

To print only those lines containing matches that form whole words you can use –w option
with grep.
grep –w ―fried‖ poem.txt
Note:
Mary fried a lot of spam
Now that we have skimmed over the basic functions of the commands in the grep family, we
can look at a few examples of more advanced functionality. The following example is an
example of grepping through the output of another program rather than a file. This particular
example will print out the files that find returns that contain the text "hello" (although this
$ find | grep "hello"
could be done without using grep at all)
Normally, grep does not have a way to search through portions of files, but when the file is
first processed by another program, this is possible. This example performs a grep on the last
8 lines
$ tailof-n8
file1.
file1 | grep "boo"
By using the exec switch with the find command, we can find files that contain the search
string. The following will search for the string "boo" in every directory below the current
directory
$ find . -exec grep "boo" {} \;
grep is the only command of the three that supports back references and saving. The
following uses back references to find lines that contain two of the same lowercase letter in
succession.
$ grep "\([a-z]\)\1" file1

egrep EXTENDED GLOBAL REGULAR EXPRESSIONS PRINT

While grep supports a handful of regular expression commands, it does not support certain
useful sequences such as the + and ? operators. If you would like to use these, you will have to
use extended grep (egrep). Egrep is equivalent to grep -E, but as it is fairly common to want
the extended functionality, egrep is also its own separate command. The Following command
131

illustrates the ?, which matches 1 or 0 occurrences of the previous character


$ grep "boots?" file1
This query will return
boot
boots
One of the more powerful constructs that egrep supports that grep does not use the pipe (|),
which functions as an "or." another way I could get the same result as above with a different
query is:
$ egrep
egrep"boot|boots"

It is a program which scans a specified file line by line and returns lines that contain a pattern
matching a given regular expression.
EXAMPLES
To specify a set or range of characters use braces. To negate the set, use the hat symbol ^ as
the first character. For example
1. [a9A05] is the set { a, 9, A, 0, 5 }
2. [^a9A05] is the complementary set ASCII - { a, 9, A, 0, 5 } (everything except a, 9, A,
0 and 5).
3. [a-z] is the set of all lowercase letters { a, b, c, d, ..., z }
4. [^a-z4-9QR] is the set of all ASCII letters except for the lowercase letters, the numerals
between 4 and 9, and the uppercase letters Q and R.

Some more examples:


$ egrep ‗^(0|1)+ [a-zA-Z]+$' searchfile.txt
match all lines in searchfile.txt which start with a non-empty bitstring, followed by a space,
followed by a non-empty alphabetic word which ends the line
$ egrep -c ‗^1|01$' lots_o_bits
count the number of lines in lots_o_bits which either start with 1or end with 01
$ egrep -c '10*10*10*10*10*10*10*10*10*10*1' lots_o_bits
count the number of lines with at least eleven 1 's

$ egrep -i '\<the\>' myletter.txt


list all the lines in myletter.txt containing the word the insensitive of case.
132
ANCHORS
Anchors are special Regular Expression characters that are used to match
a^ position
Match thein beginning
the text and
of not any character of the text.
a line

$ Match the end of a line


To search for people with the ID number 567 in our telephone.txt we use $ egrep '567$'
phonelisttxt
This looks for lines with the number 567 at the end of the line.

Multipliers
A multiplier determines how often a single character pattern must occur in the text.
Description grep egrep
zero or more times * *
one or more times \{1\} +
zero or one time \? ?
n to m times \{n,m\}

To match a line that starts with a 1, has some digits, at least one space and a name that starts
with a K we can write:
$ grep '^1[0-9]\{1,\} \{1,\} K‘ phonelist.txt
or
$ grep ‗^1[0-9] [0-9]* *K' phonelist.txt
Or
/\

Multiplier
$ egrep ‗is1used to +K'
[0-9]+ multiply the occurrence of the preceding single character pattern. So
phonelist.txt
―12*3‖ does not mean ― 1 then 2 anything 3‖ (this would be 12.*3‖)
Simply it means ―One 1 then there may be Many 2s and One 3‖
Alternation
With the | metacharcter, the or you can merge several regexes into a single regex. With this
you supply the regex engine with alternatives. Jack and Jill are two separate regexes, whereas
jack|jill is one that will match either.
Fgrep
Fgrep is the third member of the grep family. It stands for "fast grep". Fgrep is faster than
other grep commands because it does not interpret regular expressions, it only searches for
strings of literal characters. FGREP is equivalent to grep -F. If we. fgreped for boot|boots,
rather than interpreting that as a search for either the word boot or the word boots, frep would
simply search for the literal string "boot|boots" in the file. For instance, with normal grep the
following command would search for lines ending with the word "broken"
133
# fgrep "broken$" file1

However, we can see that with fgrep, it will return the line "broken$tuff" because it is not
interpreting the dollar sign, only the entire string as literal characters. It is a good practice to
use fgrep instead of grep for situations like these.
fgrep command is used to search one or more files for lines that match the given string or
word. fgrep is faster than grep search, but less flexible: it can only find fixed text, not regular
expressions.
The Syntax is
# fgrep [options] pattern [file]

Options
-a Don't suppress output lines with binary data, treat as text.

-b Print the byte offset of input file before each line of output.

-c Print's the count of line matched.


Print matched lines but not filenames.
-h
Ignore changes in case; consider upper- and lower-case letters equivalent.
-i
-n Print line and line number.
-q Prints in quite, mode, prints nothing.

-r Recursively read all files in directories and in subdirectories found.

-v Prints all the lines that do not match.


-V Print Version
Match on whole word only
-w

EXAMPLE:
fgrep -i root /etc/passwd Search for root in the file /etc/passwd.

ps -ef | fgrep -i daemon Search for daemons in the process list.


fgrep -v root /etc/passwd Display all lines except the ones containing
root

You can use fgrep to find all the lines of a file that contain a particular word. For example, to
list all the lines of a file named myfile in the current directory that contain the word "dog",
enter at the Unix prompt:
134

$ fgrep dog myfile


This will also return lines where "dog" is embedded in larger words, such as "dogma" or
"dogged". You can use the -w option with the grep command to return only lines where "dog"
is included as a separate word:
$ grep -w dog myfile
To search for several words separated by spaces, enclose the whole search string in quotes, for
example:
$ fgrep "dog named Checkers" myfile
The fgrep command is case sensitive; specifying "dog" will not match "Dog" or "DOG". You
can use the -i option with the grep command to match both upper-and lowercase letters: $
grep -i dog myfile
To list the lines of myfile that do not contain "dog", use the -v option: $ fgrep -v dog myfile
If you want to search for lines that contain any of several different words, you can create a
second file (named secondfile in the following example) that contains those words, and then
use the -f option:
$ fgrep -f secondfile myfile
You can also use wildcards to instruct fgrep to search any files that match a particular pattern.
For example, if you wanted to find lines containing "dog" in any of the files in your directory
with names beginning with "my", you could enter:
$ fgrep dog my*
This command would search files with names such as myfile, my.hwl, and mystuff in the
current directory. Each line returned will be prefaced with the name of the file where the
match was found.
By using pipes and/or redirection, you can use the output from any of these commands with
other Unix tools, such as more, sort, and cut. For example, to print the fifth word of every line
of myfile containing "dog", sort the words alphabetically, and then filter the output through
theIfmore
you command
want to save
forthe output
easy in a you
reading, file would
in the current
enter atdirectory named newfile, enter:
the prompt:
$ fgrepdog
$ fgrep dogmyfile
myfile| |cut
cut-f5
-f5-d"
-d"""| |sort
sort| > newfile
more
SED - STREAM EDITOR
sed is a non interactive, or stream editor that interprets a script and performs the actions
written by the programmer in the script, sed is stream-oriented because input flows through
the program and directed to standard output.
135
Stream Editor performs basic transformations on text. The result from sed is sent to the
standard output. The syntax for the sed command has no output file specification; still results
can be saved to a file using output redirection. SED does not modify the original input.
Sed is a non-interactive context editor that runs on all Linux flavors and UNIX-Like operating
systems.
SED is also called a batch editor and a descendant of the UNIX editor, ed.
The syntax for this utility is:
# sed [options] '{command}' [filename]
HOW SED IS DIFFERENT FROM OTHER EDITORS
1. Ability to filter text that it receives from a pipeline.
2. No need to interact with the editor while it is running.
3. Excellent in performing repetitive editing tasks.
4. SED isTO
WHERE excellent when in search and replace is performed on text.
USE SED?
Sed is designed to be especially useful in these three cases:
1. To edit files too large for comfortable interactive editing;
2. To edit any size file when the sequence of editing commands is too complicated to be
comfortably typed in interactive mode.
3. To perform multiple 'global' editing functions efficiently in one pass through the input.
4. Editing one or more files automatically.
5. Simplifying repetitive edits to multiple files.
6. Writing conversion programs.

SUBSTITUTION COMMAND
The "s" command substitutes the text with another.

$ 's/Hello/Hi/g' filename
Here, "g" at the end stands for "global". It means to replace every occurrence on the line. If we
leave it, only the first occurrence on each line will be changed.
REGULAR EXPRESSIONS
1) ‗^‘character means the BEGINNING OF THE LINE.
$ sed 's/^Fri /Friday/' Days.txt
It will turn "Fri" into "Friday", but only at beginning of the line because "g" flag is not used
and therefore we can't have multiple beginnings of a line.
2) The '$' character means the END OF THE LINE.
$ sed 's/ $//' filename
It will replace every space character which occurs at the end of a line.
136

3) Square Brackets "[ ]" specify any one of a number of characters. It is useful when we don't
know whether a letter will be upper or lower case:
$ sed 's/[Hh]i[Gg]ood/higood/g' filename
4) If we want to exclude a set or range of characters, we should use the‘^‘ character as the first
thing inside the brackets:
$ sed `s/ [ ^B-DNM-Y]\. //g` filename
It will delete any middle initials that are not B, C, D. N. M...,Y.
5) A '*' character means "ANY NUMBER OF THE PREVIOUS CHARACTER". It is applied to
literal characters and to characters that are a result of using "[ ]" or '.' .
For example,
$ sed 's/ *$//' filename
It will delete all trailing spaces from each line, WHEREAS

$ sed 's/[ ]*$//' filename


Will delete any sequence of trailing tabs and spaces. It also works when using ‖[^ ]‖
AND
$ sed 's/[ ][ ^ ]*$//' filename
Will delete the last word (sequence of non-spaces) on each line.

Linux Sed Command : Does Linux Have a Search & Replace Feature?

You can use the sed command to change all occurrences of one string to another within a file,
just like the search-and-replace feature of your word processor. The sed command can also
delete a range of lines from a file. Since sed is a stream editor, it takes the file given as input,
and sends the output to the screen, unless you redirect output to a file. In other words, sed
does not change the input file. The general forms of the sed command are as follows:
Substitution sed 's/<oldstring>/<newstring>/g' <file>
Deletion sed '<start>,<end>d' <file>

Let's start with a substitution example.


Here is a sample poem.txt file
Mary had a little lamb
Mary fried a lot of spam
Jack ate a Spam sandwich
Jill want
If you had a to
lamb spamwich
change all occurrences of lamb to ham in the poem.txt file in the grep example,
enter this:
$ sed 's/lamb/ham/g' poem.txt
137

Mary had a little ham


Mary fried a lot of spam
Jack ate a Spam sandwich
Jill had a ham spamwich
In the quoted string, the "s" means substitute and the "g" means make a global change. You
can also leave off the "g" (to change only the first occurrence on each line) or specify a
number instead (to change the first no occurrences on each line).
Now let's try an example involving deletion of lines. The values for start and end can be either
a line number or a pattern to match. All lines from the start line to the end line are removed
from the output. This example will delete starting at line 2, up to and including line 3:
$ sed '2,3d' poem.txt
Mary had a little lamb
JillThis
had aexample
lamb spamwich
will delete starting at line 1, up to and including the next line containing Jack:
$ sed '1,/Jack/d' poem.txt
Jill had a lamb spamwich
The most common use of sed is to change one string of text to another string of text. But the
strings that sed uses for search and delete are actually regular expressions. This means you
can use pattern matching, just as with grep. Although you'll probably never need to do
anything like this, here's an example anyway. To change any occurrences of lamb at the end
$ sed 's/lamb$/ham/g' poem.txt > new.file
of a line to ham, and save the results in a new file, enter this:
Since we directed output to a file, sed didn't print anything on the screen. If you look at the
contents of new.file it will show these lines:
Mary had a little ham
Mary fried a lot of spam
Jack ate a Spam sandwich
JillSummary
had a lamb spamwich

The grep command searches the given file for lines containing a match to the given strings or
words. By default, grep displays the matching lines. Use grep to search for lines of text that
match one or many regular expressions, and outputs only the matching lines.
Difference between grep, egrep and fgrep?
grep command is used to search the contents of files that matches a particular criteria.
grep - basic regular expressions
egrep - uses extended regular expressions ( slowest )
fgrep - no regular expressions ( fastest )
138

egrep - same as grep -E ( extended-regexp )


fgrep - same as grep -F ( fixed-strings )

From this you can understand that both egrep and fgrep functionality can be obtained using
grep command.
egrep can be used to search 2 srings.
Example:
egrep -l "linux|windows" ./*
grep -E -l "linux|windows" ./*
or
The above command will list all the files with the words linux or windows in it.
grep Search a Pattern from current directory.

egrep (grep -E in linux) is extended grep where additional regular expression metacharacters
have been added like +, ?, | and ().

fgrep (grep -F in linux) is fixed or fast grep and behaves as grep but does not recognize any
regular expression metacharacters as being special.

Printing Commands
lpq command:
We can use lpq command to check the status of the print queue. And to view the entries in the
print queue.
lprm command
It is used to remove a print job from the print queue.
-a
Options to remove all the print jobs from the entire print queue available to the
user.
user <user_name> to
-P <printer_name> toremove
remove the
print jobjob
given bythe
specified user.
to remove print
print job from specified printer
job ID with the specified job id
Examples:
$ lprm 8
It will delete the print job with the job id 8 from the default printer.
$ lprm –P ql –U steve
It will delete all the print jobs given by user steve in the ql print queue.
lpc command
It is used by system administrators to control the operations of the print services. You can use
lpc to Disable or enable a printer, Disable or enable the print queue of a printer ,Rearrange the
jobs in a print queue and Check the status of printers their associated print queues and the
printer daemons
139

Understanding Various Servers

1. DHCP server

The dynamic host configuration protocol is a network configuration protocol for host on
internet protocol network. Computers that are connected to IP networks must be configured
before they can communicate with other host. The most essential information needed is an IP
address and a default route and routing prefix.
DHCP eliminates the manual task by a network administration. It also provides a central
database of devices that are connected to the network and eliminates duplicate resource
assignments.
In addition to IP address DHCP also provides other configuration information particularly the
IP address,
DHCP was network route on
first defined service or othertrack
a standard service host. DHCP
protocols is used
in RFC 1531for
in IPv4& IPv6.
October 1993 as an
extension to the boot strap protocol. The motivation for extending boot strap protocol was that
boot strap protocol required manual intervention to add configuration information for each
client and did not provide a mechanism for reclaiming dimmed IP addresses. DHCP is useful
because
When a itDCHP
makesconfigured
it easy to add newconnects
client machinestotoa the network.
network the DHCP client sends a broadcast
query requesting necessary information from a DHCP server. The DHCP server manages a
pool of IP addresses and information about client configuration parameters such as default
gateway, domain name, the name servers and other servers. On receiving a valid request the
server assign the computer and IP address a lease time (length of time the allocation in valid)
and other IP configuration parameters such as the subnet mask and the default gateway. The
Depending
query on implementation
is typically the DHCP
initiated immediately server may
after booting havecomplete
and must 3 methods of the
before allocating IP
client can
addresses.
initiate
1) IP based communicate
Dynamic allocation with other host.
2) Automate allocation
3) Static allocation
i. Dynamic allocation
A network administrator assigns a range of IP addresses to DHCP and each client computer
on the LAN is configured to request an IP address from the DHCP server during network
initialization. The request & grand process uses a lease concept with a controllable time
period allowing the DHCP server to reclaim and then reallocate IP addresses that are not
renewed.
140

ii. Automatic allocation


A DHCP permanently assign a free IP address to a requesting client from the range defined by
the administrator. This is like dynamic allocation but the DHCP server keeps a table of part IP
address assignments so that it can preferentially assigned to a client the name IP address that
iii. client previously
the Static allocation
had.
The DHCP server allocates an IP address based on a table with MAC (Medium Access
Control) address /IP address pair which are manually filled in. only requesting clients
allocated an IP address. This Feature (which is not supported by all DHCP servers) is
variously called static DHCP assignments, fixed address, address reservation, DHCP
2.
reservation etc
DNS Server
DNS server translate the domain names into machine readable IP address needed to locate the
requested web server on the internet. Its user interface and automation features are simple. It
is simple to use with windows Os. All options and settings are available directly from
windows user interface. It provides wizards for common taste such as setting up new zones,
importing data; making bulk update etc. you never need to deal with cryptic configuration
Users
files orcan have their
registry DNS server up and running correctly and securely. DNS server is a very
settings.
capable and full features server and it has plenty of option for expert to make it just the way
they want DNS server can optionally server.DNS records directly from a SQL server.DNS
3. comes
server SQUID
with a DHCP server plug in, a DNS look up tool and many other features.

SQUID is released in July 1996.it is a proxy server and web server. Proxy server is a server
that acts as an intermediary for request from clients seeking resources from other servers. A
client connects to the proxy requesting some service such as a file, connection, web page on
other resources available from a different server. The proxy server evaluates the request
according to its filtering rules. If the request is validated by the filter the proxy server provide
the resource by connecting to the relevant server and requesting the service on behalf of the
Web cache is a mechanism for the temporary storage of web document such as HTML pages
client.
& images to reduce band width image, server load. A web cache stores copies of documents
passing through it. Subsequent request may be satisfied from the cache of certain candies are
met.
SQUID has a wide variety of users from speeding up a web server by caching repeated
request, to caching web, DNS and other computer network look ups for a group of people
sharing network resources to adding security by filtering traffic. Also primarily used for
HTTP & FTP, SQUID includes limited support for several other protocols including TLS
(Transport Layer Security protocol), SSL (Secure Socket Layer) internet gopher and HTTPs
141

(Hyper Text Transfer Protocol Secure it is a combination of HTTP with SSL or TLS
protocol). SQUID was originally designed to run to UNIX like system, but also runs well on
windows based systems. SQUID is free software. It is used by Wikipedia.
Squid is used by 100‘s of internet provides worldwide to provide their users with the best
possible web access. Squid optimize the data flow between client and server improves
Squid can reduce
performance your server
and caches load and improve delivery speeds to clients. Squid can also be
frequently.
used to deliver content from around the world, typing only the content being used.
4) FTP Server

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one
host to another host over a TCP based network such as the internet. FTP is built on client
server architecture and utilizes separate control and data connections between the client and
server. FTP users may authenticate themselves using a clear text sign in protocol but can
connect
The firstanonymously if the server
FTP client applications is configured
where to command
interactive allow it. line tools implementing standard
commands and syntax. GUI clients have since been developed for many of popular desktop
OS inoperates
FTP use today.
on application layer of the OSI model and is used to transfer files using TCP/IP.
In order to do this an FTP server needs to be running and waiting for incoming request. The
client computer is then able to communicate with the server. This connection called control
connection remains open for the duration of the session with a second connection called the
data connection either opened by the server from its port to a client port (active mode) or
opened by the client to a server port (passive mode) as required to transfer file data. The
5) connection
control Samba server
is used for session administration. That is commands identification and
passwords
Samba exchanged
is free softwarebetween theunder
licensed clientthe
andGNU
serverGeneral
using a telnet
Publiclike protocol.
License. It is developed in
1992. Samba has provided secure stable and fast file and print services for all clients using the
SMB / CIFS protocol. (Server Message Block / Common Internet File System) works as
application layer of the network.
Samba is an important component of integrated linux or unix servers and desktops into active
directory environment. Samba is freely available unlike other SMB/CIFS implementation and
Samba is software that can be run on a platform like Microsoft windows, unix, linux, IBM
allow for interoperability between unix or linux servers and windows based clients.
system 390 and other OS. It uses the TCP/IP protocol that is installed on the host server.
When correctly configured it allows that host to interact with a Microsoft windows client or
server as if it is a windows file and print server.
It is a software package that gives network administrator flexibility and freedom in terms of
Samba is a free software re-implementation of the SMB/CIFS networking protocol, originally
set up configuration and choice of system and equipment.
142

developed by Andrew Tridgell. As of version 3, Samba provides file and print services for
various Microsoft Windows clients and can integrate with a Windows Server domain, either
as a Primary Domain Controller (PDC) or as a domain member. It can also be part of an
Active Directory domain.
Samba runs on most Unix and Unix-like systems, such as GNU/Linux, Solaris, AIX and the
BSD variants, including Apple's Mac OS X Server (which was added to the Mac OS X client
in version 10.2). Samba is standard on nearly all distributions of Linux and is commonly
included as a basic system service on other Unix-based operating systems as well. Samba is
released under the GNU General Public License. The name Samba comes from SMB (Server
FEATURES
Message Block), the name of the standard protocol used by the Microsoft Windows network
file system.
Samba allows file and print sharing between computers running Windows and computers
running Unix. It is an implementation of dozens of services and a dozen protocols, including
the NetBIOS over TCP/IP (NBT), SMB, CIFS (an enhanced version of SMB), DCE/RPC or
more specifically, MSRPC, the Network Neighborhood suite of protocols, a WINS server also
Domain
known suite of protocols
as a NetBIOS which
Name Server includes
(NBNS), theNT
NT Domain Logons, Secure Accounts Manager
(SAM) database, Local Security Authority (LSA) service, NT-style printing service
(SPOOLSS), NTLM and more recently Active Directory Logon which involves a modified
version of Kerberos and a modified version of LDAP. All these services and protocols are
frequently incorrectly referred to as just NetBIOS or SMB. The NetBIOS and WINS protocols
Samba sets up network shares for chosen Unix directories (including all contained
subdirectories). These appear to Microsoft Windows users as normal Windows folders
accessible via the network. Unix users can either mount the shares directly as part of their file
structure using the smbmount command or, alternatively, can use a utility, smbclient (libsmb)
installed with Samba to read the shares with a similar interface to a standard command line
FTP program. Each directory can have different access privileges overlaid on top of the
normal Unix file protections. For example: home directories would have read/write access for
all known users, allowing each to access their own files. However they would still not have

Samba services are implemented as two daemons:

 smbd, which provides the file and printer sharing services, and

 nmbd, which provides the NetBIOS-to-IP-address name service. NetBIOS over TCP/IP
requires some method for mapping NetBIOS computer names to the IP addresses of a TCP/IP
143
Samba configuration is achieved by editing a single file (typically installed as /etc/smb.conf or
/etc/samba/smb.conf). Samba can also provide user logon scripts and group policy
implementation through poledit.
Samba is included in most Linux distributions and is started during the boot process. On Red
Hat, for instance, the /etc/rc.d/init.d/smb script runs at boot time, and starts both daemons. Samba

Samba includes a web administration tool called Samba Web Administration Tool (SWAT).

6) APPACHE

Apache is the most widely used HTTP-server in the world today. It surpasses all free and
commercial competitors on the market, and provides a myriad of features; more than the
nearest competitor could give you on a UNIX variant. It is also the most used web server for a
Linux system. A web server like Apache, in its simplest function, is software that displays and
serves HTML pages hosted on a server to a client browser that understands the HTML code.
Mixed with third party modules and programs, it can become powerful software, which will
FEATURES
provide strong and useful services to a client browser.

Apache supports a variety of features, many implemented as compiled modules which extend
the core functionality. These can range from server-side programming language support to
authentication schemes. Some common language interfaces support Perl, Python, Tcl, and
PHP. Popular authentication modules include mod_access, mod_auth, mod_digest, and
mod_auth_digest, the successor to mod_digest.
A sample of other features include Secure Sockets Layer and Transport Layer Security
support (mod_ssl), a proxy module (mod_proxy), a URL rewriter (also known as a rewrite
engine, implemented under mod_rewrite), custom log files (mod_log_config), and filtering
support (mod_include and mod_ext_filter).
Popular compression methods on Apache include the external extension module, mod_gzip,
implemented to help with reduction of the size (weight) of web pages served over HTTP.
ModSecurity is an open source intrusion detection and prevention engine for web
applications. Apache logs can be analyzed through a web browser using free scripts such as
AWStats/W3Perl or Visitors.
144

Virtual hosting allows one Apache installation to serve many different actual websites. For
example, one machine with one Apache installation could simultaneously serve
www.example.com, www.example.org, test47.test-server.example.edu, etc.
Apache features configurable error messages, DBMS-based authentication databases, and
content negotiation. It is also supported by several graphical user interfaces (GUIs).
It supports password authentication and digital certificate authentication. Apache has a built in
search engine and an HTML authorizing tool and supports FTP.
Performance

Although the main design goal of Apache is not to be the "fastest" web server, Apache does
have performance similar to other "high-performance" web servers. Instead of implementing a
single architecture, Apache provides a variety of Multiprocessing Modules (MPMs) which
allow Apache to run in a process-based, hybrid (process and thread) or event-hybrid mode, to
better match the demands of each particular infrastructure. This implies that the choice of
correct MPM and the correct configuration is important. Where compromises in performance
need to be made, the design of Apache is to reduce latency and increase throughput, relative to
simply handling
The Apache moreconsidered
version requests, by
thus
theensuring
Apacheconsistent
Foundationand
as reliable processing
providing of requests
high-performance is
within reasonable time-frames.
the multi-threaded version which mixes the use of several processes and several threads per
process. This architecture, and the way implemented in Apache 2.4.0, provides for
performance at least equal to other event-based web servers.
7) TELNET

telnet server is used to login into another system. You can use the telnet command to log in
remotely to another system on your network. The system can be on your local area network or
available through an Internet connection. Telnet operates as if you were logging in to another
system from a remote terminal. You will be asked for a login name and password. In effect,
you are logging in to another account on another system. In fact, if you have an account on
another system,
You invoke the you could
Telnet use with
utility Telnetthetokeyword
log in to telnet.
it. If you know the name of the site you
want to connect with, you can enter telnet and the name of the site on the Linux command
line.
Telnet is a network protocol used on the Internet or local area networks to provide a
bidirectional interactive text-oriented communications facility using a virtual terminal
connection. User data is interspersed in-band with Telnet control information in an 8-bit byte
oriented data connection over the Transmission Control Protocol (TCP).
145

Telnet was developed in 1969 beginning with RFC 15, extended in RFC 854, and
standardized as Internet Engineering Task Force (IETF) Internet Standard STD 8, one of the
first Internet standards.
Historically, Telnet provided access to a command-line interface (usually, of an operating
system) on a remote host. Most network equipment and operating systems with a TCP/IP
stack support a Telnet service for remote configuration (including systems based on Windows
NT). Because of security issues with Telnet, its use for this purpose has waned in favor of
SSH.
The term telnet may also refer to the software that implements the client part of the protocol.
Telnet client applications are available for virtually all computer platforms. Telnet is also used
as a verb. To telnet means to establish a connection with the Telnet protocol, either with
command line client or with a programmatic interface. For example, a common directive
might be: "To change your password, telnet to the server, login and run the passwd
command." Most often, a user will be telnetting to a Unix-like server system or a network
device (such as a router) and obtain a login prompt to a command line text interface or a
character-based full-screen manager.

You might also like