0% found this document useful (0 votes)
55 views72 pages

1736405993-Linux Notes

The document provides an overview of the Linux operating system, detailing its functions, architecture, and history, including its development from UNIX. It explains key concepts such as process management, memory management, and file management, as well as the differences between single-user and multi-user systems. Additionally, it discusses the various shells available in Linux and highlights the features and utilities that make Linux a popular choice among operating systems.

Uploaded by

supravat.p2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views72 pages

1736405993-Linux Notes

The document provides an overview of the Linux operating system, detailing its functions, architecture, and history, including its development from UNIX. It explains key concepts such as process management, memory management, and file management, as well as the differences between single-user and multi-user systems. Additionally, it discusses the various shells available in Linux and highlights the features and utilities that make Linux a popular choice among operating systems.

Uploaded by

supravat.p2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

CORE 7: LINUX AND SHELL PROGRAMMING

UNIT I
LINUX OPERATING SYSTEM
INTRODUCTION
Operating system:
⮚ An operating system (OS) is a program that acts as an interface between a user and a computer by
accepting input from the user, interpreting the input and generating output.
⮚ The OS manages computer hardware and system resources such as memory and hard disk.
⮚ The OS forms the base on which any application software is developed.
Some popular operating systems are:
● Linux
● Unix
● MSDOS
● MS windows 95/98
● MS windows NT server 4.0
● Apple max

Functions of an Operating System


1. Command interpretation
2. Process management
3. Memory management
4. Input output operations and peripheral management
5. File management

1. Command Interpretation
The CPU interprets commands entered by a user to perform tasks such as copying or deleting files.
The OS translates the command to binary code so that the CPU can interpret the command.
Note :The CPU can interpret only binary code which comprises of 0’s and 1’s.

2. Process Management
A process operating system is defined as a program in execution.
To run a program needs to be in the main memory called RAM.
When you run a program the OS loads the program in the memory and the CPU executes one
instruction at a time.
In a multi programming environment many process run on the computers (at the same time) or
simultaneously, where the CPU time is divided.
The OS allocates time slots to the different processes in the memory which facilitates process
execution.

3. Memory Management
1
Stores the processes that are not being executed The OS allocates the available memory to the
processes.
As the main memory is limited, it is not possible to load all the processes at a given time.
The main memory stores the processes that ate currently running and the hard disks.
The hard disk is used as a temporary storage device.
Processes can be run only when they are in the main memory and theme the OS maps the
processes from the hard disk to the main memory.

4. Input Output Operations and Peripheral Management


When an application is executed it accepts input and produces output.
Applications cannot perform these operations directly.
Therefore the OS enables the input-output devices such as the keyword, the mouse or the printer to
perform these input-output operations.
An OS also controls the devices attached to the computer. These devices are known as peripherals.
The OS manages communication between the devices and the CPU. Eg: An OS manages
communication between the printer or the modem and the CPU.

5. File Management
Another X, feature of an OS is file management. The OS enables you to perform file operation
such as creating, naming, opening, reading and closing a file.

Types of Systems
i) Single User Systems
ii) Multi User Systems
i) Single User Systems
A single user system can only be used by one person at a time.
An example of a single user system is a personal computer (PC).
The PC is a popular single user system which is small, general purpose computer that can run
program to perform a wide variety of tasks.
Due to the low cost of the hardware requirements and a wide range of available software, the PC
has become very popular.
Single User Operating Systems:
MSDOS is an e.g. of single user OS which has a command line interface (CLI).
Note:
A CLI display data character by character and is only text based. A GUI display text as well as icons
and images. GUI based software is slower than CLI but is more user friendly.

ii) Multi User Systems


More than one user can work simultaneously.
Multi User Systems can run multiple process concurrently and share hardware resources such as
printers and disks.

Users can use the system console or terminal to connect to the multi user system.
Remote users can use communication lines of a telephone and connect to a multi users system.
Many users can share a printer connected to a multi user system.

BASIC CONCEPTS OF A MULTI USER SYSTEMS

2
The CPU of a multi user system is more powerful than that of a single user system.
Two essential features of multi user system are multi programming and multi tasking. For example,
having a cup of coffee, reading a book and talking to a friend over the phone, i.e. performing more than
one task simultaneously. However at a given time, either one could sip coffee, read the book or speak over
the phone by dividing time into smaller units and in each unit of time one task is done. Similarly the CPU
divides the time between all the active tasks.
A multiuser system consists of a computer with several terminals attached which enables various
users to work on the computer.

Terminals are of 2 types :


1) Dumb terminals
2) Smart Terminals
A Dumb terminal consists of a monitor and a keyboard and has no hard disk or CPU.
The dumb terminal only acts as an interface between a user and the multi user and the multi user system .
In the case of dumb terminal, the multi user system process all the requirements.
A smart terminal has its own CPU and peripherals and can work independent of the multi user system.
A smart terminal can work on any OS that is loaded on to its hard dosk .
It can also be connected to the central unit when required.
Eg: assume that you are working on a computer running windows NT using the resources such as hard
disk memory and processor of the local computer.
When you connect and work on another computer running linux / UNIX, you start using all the resources
of the linux / UNIX computer.

Note : The hard disk usually has the capacity to store a large amount of data because many users share
a multi user system.

Multi user operating system


Linux, UNIX and windows NT terminal server are examples of multi user Operating SystemS. In such
systems more than one user can connect to the system and work concurrently at any given time .

Note : windows 95 is a multitasking OS but not a multi user system. It can run simultaneously run
multiple tasks, but it does not allow multiple user to connect to do all a given time.

THE LINUX OPERATING SYSTEM


The history of linux
In 1969 , ken Thompson and Dennis Ritche developed a small, general purpose OS called UNIX.
Traditionally all OS were written in assembly language and SO uses UNIX .
In 1973, Thompson and Ritche rewrote the UNIX OS in C.
In 1974, UNIX was licensed to universities for educational purposes and then for commercial purpose.
Many vendors such as sun, IBM and Hewlett – Packard (HP) purchased the source code of UNIX and
developed their own version of UNIX. Most of their versions were proprietary and maintained by their
respective hardware vendors. The source code of these versions was not freely available, so the developers
had to wait for a long time for the release of bug fixes.
● In 1984, Richard Stallmans Free Software Foundation (FSF) began the GNU (GNUS NOT
UNIX ) project to create a free version of the UNIX OS .
● The FSF built a number of tools that could be used freely, read, modified and redistributed.
● By 1990, the FSF developed a number of tools but the kernel was still not created.
● In 1991, Linus Torvalds developed a kernel and called it Linux.

3
● In 1992, the Linux Kernel was combined with the incomplete GNU system to form a
completely free OS .
● This OS called GNU/Linux is a combination of GNU and Linux .
● The GNU/Linux OS is commonly referred to as Linux OS.

Few distributors of linux are :

S.No Distributor Name Website


.
1. Red Hat http:// www.redhat.com
2. Caldera http:// www.caldera.com
3. Mandrake http:// www.mandrake.com
4. Debian http:// www.debian.com
5. Suse http:// www.suse.com
6. Stackware http:// www.stackware.com

Linux follows the open development model. Therefore the current development version of Linux is
always available open to users. Users can also suggest modifications to the kernel code. When a new
version of Linus Torvalds ensures strict quality control and then merges all the new code into the kernel.
This is an contrast to a closed model in which a project team develops a particular software version and
waits before users can work on softwares and report bugs. The project team then fixes the bugs and
releases a new version. This is the major reason for the success of Linux. Linux has an official mascot –
the Linux penguin – called tux. Linux has free software such as text editors browsers and programming
tools.

LINUX ARCHITECTURE
The GNU/Linux OS consists of a kernel, a shell, utilites and apply programs.
The architecture of the Linux OS is displayed in Figure 1.1.

SHELL UTILITIES APPLICATION


PROGRAM

KERNEL

HARDWARE

Figure 1.1 : Components of the Linux OS

KERNEL :
The core of the Linux system is the kernel which is also the operating system program. The kernel
controls the resources of a computer allocating them to different users and tasks. It interacts directly with
the hardware, making programs easy to write and portable across different hardware platform. However
4
the users do not interact directly with a kernel. Instead the logon process initiates a separate, interactive
program called the shell for each user.

SHELL :
Linux has a simple user interface called the shell. The shell provides services for the user. A user
interacts with the computer by using the shell. The user need not know about the intricate details of the
hardware. Some common shells in Linux are bash, sh, tcsh, csh and ksh.

LINUX UTILITIES AND APPLICATION PROGRAM :


Linux utilities or commands are a collection of programs that service processing requirements.
These programs can be started by using the shell. In addition to the utilities that are a part of the Linux OS,
many Linux based applications program such as DBMS and word processors are available from
independent software vendors.

LINUX COMPARED TO 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 also considered as another version of Unix. The main
difference between Linux and Unix is that Linux is free of cost. However varies distributors of Linux can
charge a price for Linux. In addition Linux does not involve any licencing issues. Linux has developed
tools such as C, C++, FORTRAN, PASCAL and scripting languages such as awk, perl, python. Many of
scripting languages are free of cost. In addition, web sewers such as apache and browsers such as
Netscape provide their version that are compatible with Linux, free of cost .
comparison between Linux and Unix :

FEATURES LINUX UNIX


Shell available Bash, pdksh, tcsh, zsh, ash. Bourne, korn, C.
Variants Red hat, caldera, debian, linux AT and T, MULTICS, BSD,
PPC, suse. SCO, HP, UX, IRIX, UHRIX,
XENIX, Sunsolaris.
Licencing Freely distributed Expensive licencing.

FEATURES AND UTILITIES IN LINUX :


Some of the features of Linux OS are :
● Multiprogramming
● Time sharing
● Multi tasking
● Virtual memory

Multiprogramming :

Linux allows several programs to be executed simultaneously by different users.

Time sharing :

5
Multiprogramming is possible on the Linux system due to the concept of time sharing. In time
sharing, the OS manages various programs simultaneously. Programs are queued and CPU time for
specific period and it is then replaced in the queue.

Multitasking :

A program in Linux is broken down into tasks such as reading from or writing to the disk or
waiting for input from a user. The ability of any OS to handle the execution of multiple tasks is known as
multi tasking .
When a task is waiting for the completion of another task, the CPU, instead of waiting time, starts
executing the next task. Therefore while one task is waiting for input from the user, another task could be
reading from the hard disk. The kernel is responsible for scheduling the tasks. The amount of physical
memory might not always be sufficient to execute large apply or enable multiple apply to be active at a
given time.
In such situation a partition that is a logical position of the hard disk can be utilized as artificial or
virtual memory. That is the OS places the programs and data which are not frequently used in this portion
of the hard disk and loads them in the memory whenever required.Therefore the OS uses the resources of
the computer optimally.

Utilities :

● Samba
● Cron scheduler
● Licencing
● Web server .

Samba :
● The name samba is derived from the server message block protocol or SMB.
● SMB is the protocol used by Microsoft OSs to share files and printers.
● Samba is a suit of programs that implement the SMB protocol on Linux
● Using samba Linux file system can be shared with windows 95, windows 98 or windows
NT.
● Also you can also share a windows 95/98/NT file system with linux.
● Similarly, SMB can be used to share printers connected to windows 95/98 NT computers
with Linux.

1. Note : A Protocol is a set of rules that specify the communication standards for data transfer.
2. A file system is a mechanism used by an OS to store and manage files and directories on a
storage medium.

Cron scheduler :
▪ Linux has a scheduler program called cron.
▪ Cron is used to run commands, scripts or programs at scheduled times.

Licensing :
▪ Linux is licensed under the GNU general public license.
▪ The licensing for red hat linux states that a person can make any number of copies
of software and distribute it freely or charge a price for it.

6
▪ Linux can also be downloaded free of cost from the internet.

Web server :
● Web server is a process that runs on the OS and enables users to access resources
that have been published in the form of web pages.
● A web server can enable users to access resources on a wide area network (WAN )
or the internet.
● A web server is commonly referred to as a computer that delivers web pages.
● Linux OS comes with the apache web server.
● For example : when the address of a web site is typed say www.apache.org in a web
server, the apache web server sends the home page of the web site to your
computer.

Shells available in Linux :


In Linux, the shell runs like any other program.Various shells available for unix/ Linux are,

▪ Bourne shell
▪ C shell
▪ Korn shell
▪ Restricted shell
▪ Bash shell
▪ Tcsh shell
▪ A shell
▪ Z shell

1) Bourne shell
o The Bourne shell was developed by Stephen R .Bourne at AT & T and named after the developer,
Bourne.
o The Bourne shell is distributed in all the UNIX systems and is stored in the /bin directory.
o The executable file name for Bourne shell is sh which is one of the most widely used shells for
UNIX systems.
2) C Shell
o The C shell was developed by William Joy at the University of California at Berkeley to provide
a programming interface similar to the c programming language.
o The executable file name for C shell is csh.
o The C shell derives its name from its programming language which resembles the C
programming language in syntax.
3) Korn Shell
o The Korn Shell, developed by David Korn at AT&T and named after him.
o The Korn Shell combines the features of bourne shell and C shell.
o The executable file name for the korn shell is ksh .
4) Restricted shell :
o To provide limited access on the OS to a user, the restricted shell can be used.
o Used for guest users to provide limited rights and permissions.
o In addition, the restricted shell is used to restrict the users of the OS to a limited
environment.
5) Bash shell :
o The bash shell is an enhancement on the bourne shell.

7
o Bash is an acronym for Bourne Again Shell.
o Bash is a product of Free Software Foundations GNU project the bash shell is the
default shell for most Linux systems and stored in the / bin directory.the bash shell
stores all the commands that is used in a session.
o In addition the bash shell also stores the commands used in the previous sessions.
o In red hat Linux the sh command is a symbolic link to bash.
6) Tcsh shell :
o Tcsh stands for tom’s C shell and is an enhancement of the C shell.
o The Tcsh shell is also known as the TC shell.
o In Linux, the csh command is symbolic link to the Tcsh shell.
o To execute the TC sh shell type either csh or Tcsh at the command prompt

7) A shell :
o The A shell was developed by Kenneth Almquist of the University of Berkeley.
o It emulates the bourne shell
o The A shell is suitable for computers with limited memory.
o The executable file for A shell is ash.

8) Z shell :
o The Z shell offers the features of Tcsh and Korn shells.
o In addition, it provides a large number of utilities and extensive documentation.
o The executable file name for the Z shell is Zsh.

Beginning a Linux session : logging on

The telnet program is used to connect to a computer running the Linux operating system
from a computer running windows 95/98/NT operating systems .
To launch the telnet program type the following command at the command prompt
telnet <host name or IP address >

for example: to connect a working computer running the windows 95 OS and the TCP/IP address
assigned to the Linux server were 192.168.0.1 then give the folly, command to connect to the
Linux server.

telnet 192.168.0.1
after connecting to the Linux server, the folly message appears on the screen.

Red hat Linux server 7.1( sea wolf ) kernel 2.4 2-2 o an 686 login :
Logon :

Each user has an identification called the user name or the logon name. The logon name is entered
by the user when the login: prompt appears on the screen.

The steps to logon to a Linux server arc:


Enter logon name and password at the login: prompt.
Information about users such as user names and passwords are stored in the shadow and password
files in the extra directory.

8
Note: when a user enters the logon name and password, the user name and password are checked
in shadow and password files.

If the login : information provided by the user does not match the information in the shadow and
password files, an error message” login incorrect “ is displayed. Thus, this check ensures that only
authorized users access the system.
When a valid user name and password are entered, the shell prompt is displayed on the screen as
given below.
user_name@ localhostcurrent_directory_name.
$ is the shell prompt.
At the shell prompt, the user_name is the logon nae of the user and current_directory_name is the
current working directory of the user.
When a user logon account is created, the administrator assigns a home directory to the user.

Unit II

Unix / Linux - Directory Management


A directory is a file that stores the file names and the related information. All the files, whether
ordinary, special, or directory, are contained in directories.

Unix uses a hierarchical structure for organizing files and directories. This structure is often referred to as
a directory tree. The tree has a single root node, the slash character (/), and all other directories are
contained below it.

Home Directory
The directory in which you find yourself when you first login is called your home directory.

You will be doing much of your work in your home directory and subdirectories that you'll be creating to
organize your files.

You can go in your home directory anytime using the following command −

$cd ~
$

Here ~ indicates the home directory. Suppose you have to go in any other user's home directory, use the
following command −

$cd ~username
$

To go in your last directory, you can use the following command −

$cd –
$

9
Absolute/Relative Pathnames
Directories are arranged in a hierarchy with root / at the top. The position of any file within the hierarchy
is described by its pathname.

Elements of a pathname are separated by a /. A pathname is absolute, if it is described in relation to root,


thus absolute pathnames always begin with a /.

Following are some examples of absolute filenames.

/etc/passwd
/users/sjones/chem/notes
/dev/rdsk/Os3

A pathname can also be relative to your current working directory. Relative pathnames never begin with /.
Relative to user amrood's home directory, some pathnames might look like this −

chem/notes
personal/res

To determine where you are within the filesystem hierarchy at any time, enter the command pwd to print
the current working directory −

$pwd
/user0/home/amrood

Listing Directories
To list the files in a directory, you can use the following syntax −

$ls dirname

Following is the example to list all the files contained in /usr/local directory −

$ls /usr/local

X11 bin gimp jikes sbin


ace doc include lib share
atalk etc info man ami

Creating Directories
We will now understand how to create directories. Directories are created by the following command −

$mkdir dirname

Here, directory is the absolute or relative pathname of the directory you want to create. For example, the
command −

10
$mkdir mydir
$

Creates the directory mydir in the current directory. Here is another example −

$mkdir /tmp/test-dir
$

This command creates the directory test-dir in the /tmp directory. The mkdir command produces no
output if it successfully creates the requested directory.

If you give more than one directory on the command line, mkdir creates each of the directories. For
example, −

$mkdir docs pub


$

Creates the directories docs and pub under the current directory.

Creating Parent Directories


We will now understand how to create parent directories. Sometimes when you want to create a directory,
its parent directory or directories might not exist. In this case, mkdir issues an error message as follows −

$mkdir /tmp/amrood/test
mkdir: Failed to make directory "/tmp/amrood/test";
No such file or directory
$

In such cases, you can specify the -p option to the mkdir command. It creates all the necessary directories
for you. For example −

$mkdir -p /tmp/amrood/test
$

The above command creates all the required parent directories.

Removing Directories
Directories can be deleted using the rmdir command as follows −

$rmdir dirname
$

Note − To remove a directory, make sure it is empty which means there should not be any file or sub-
directory inside this directory.

You can remove multiple directories at a time as follows −

$rmdir dirname1 dirname2 dirname3


$
11
The above command removes the directories dirname1, dirname2, and dirname3, if they are empty. The
rmdir command produces no output if it is successful.

Changing Directories
You can use the cd command to do more than just change to a home directory. You can use it to change to
any directory by specifying a valid absolute or relative path. The syntax is as given below −

$cd dirname
$

Here, dirname is the name of the directory that you want to change to. For example, the command −

$cd /usr/local/bin
$

Changes to the directory /usr/local/bin. From this directory, you can cd to the directory
/usr/home/amrood using the following relative path −

$cd ../../home/amrood
$

Renaming Directories
The mv move

command can also be used to rename a directory. The syntax is as follows −

$mv olddir newdir


$

You can rename a directory mydir to yourdir as follows −

$mv mydir yourdir


$

The directories . dot and .. dotdot


The filename . dot

represents the current working directory; and the filename .. dotdot

represents the directory one level above the current working directory, often referred to as the parent
directory.

If we enter the command to show a listing of the current working directories/files and use the -a option to
list all the files and the -l option to provide the long listing, we will receive the following result.

$ls -la

12
drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 .
drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
---------- 1 teacher class 4210 May 1 08:27 .profile
-rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo
$

File management in Unix/Linux : All data in Unix is organized into files. All files are organized into
directories. These directories are organized into a tree-like structure called the filesystem.

When you work with Unix/Linux, one way or another, you spend most of your time working with files.

In Unix/Linux, there are three basic types of files −

● Ordinary Files − An ordinary file is a file on the system that contains data, text, or program
instructions. In this tutorial, you look at working with ordinary files.
● Directories − Directories store both special and ordinary files. For users familiar with Windows or
Mac OS, Unix directories are equivalent to folders.
● Special Files − Some special files provide access to hardware such as hard drives, CD-ROM
drives, modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and
enable you to access a single file using different names.

Listing Files
To list the files and directories stored in the current directory, use the following command −

$ls

Here is the sample output of the above command −

$ls

bin hosts lib res.03


ch07 hw1 pub test_results
ch07.bak hw2 res.01 users
docs hw3 res.02 work

The command ls supports the -l option which would help you to get more information about the listed files

$ls -l
total 1962188

drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml


-rw-rw-r-- 1 amrood amrood 5341 Dec 25 08:38 uml.jpg
drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ
drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia
-rw-r--r-- 1 root root 276480 Dec 9 2007 urlspedia.tar
drwxr-xr-x 8 root root 4096 Nov 25 2007 usr
drwxr-xr-x 2 200 300 4096 Nov 25 2007 webthumb-1.01
-rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php
-rw-rw-r-- 1 amrood amrood 20480 Nov 25 2007 webthumb.tar
-rw-rw-r-- 1 amrood amrood 5654 Aug 9 2007 yourfile.mid
-rw-rw-r-- 1 amrood amrood 166255 Aug 9 2007 yourfile.swf
13
drwxr-xr-x 11 amrood amrood 4096 May 29 2007 zlib-1.2.3
$

Here is the information about all the listed columns −

● First Column − Represents the file type and the permission given on the file. Below is the
description of all type of files.
● Second Column − Represents the number of memory blocks taken by the file or directory.
● Third Column − Represents the owner of the file. This is the Unix user who created this file.
● Fourth Column − Represents the group of the owner. Every Unix user will have an associated
group.
● Fifth Column − Represents the file size in bytes.
● Sixth Column − Represents the date and the time when this file was created or modified for the
last time.
● Seventh Column − Represents the file or the directory name.

In the ls -l listing example, every file line begins with a d, -, or l. These characters indicate the type of the
file that's listed.

S.No. Prefix & Description


1 - Regular file, such as an ASCII text file, binary executable, or hard link.
2 b - Block special file. Block input/output device file such as a physical hard drive.
3 c - Character special file. Raw input/output device file such as a physical hard drive.
4 d - Directory file that contains a listing of other files and directories.
5 l - Symbolic link file. Links on any regular file.
6 p - Named pipe. A mechanism for interprocess communications.
7 s - Socket used for interprocess communication.

Metacharacters
Metacharacters have a special meaning in Unix. For example, * and ? are metacharacters. We use * to
match 0 or more characters, a question mark (?) matches with a single character.

For Example −

$ls ch*.doc

Displays all the files, the names of which start with ch and end with .doc −

ch01-1.doc ch010.doc ch02.doc ch03-2.doc


ch04-1.doc ch040.doc ch05.doc ch06-2.doc
ch01-2.doc ch02-1.doc c

Here, * works as meta character which matches with any character. If you want to display all the files
ending with just .doc, then you can use the following command −

$ls *.doc

14
Hidden Files
An invisible file is one, the first character of which is the dot or the period character (.). Unix programs
(including the shell) use most of these files to store configuration information.

Some common examples of the hidden files include the files −

● .profile − The Bourne shell ( sh) initialization script


● .kshrc − The Korn shell ( ksh) initialization script
● .cshrc − The C shell ( csh) initialization script
● .rhosts − The remote shell configuration file

To list the invisible files, specify the -a option to ls −

$ ls -a

. .profile docs lib test_results


.. .rhosts hosts pub users
.emacs bin hw1 res.01 work
.exrc ch07 hw2 res.02
.kshrc ch07.bak hw3 res.03
$

● Single dot (.) − This represents the current directory.


● Double dot (..) − This represents the parent directory.

Creating Files
You can use the vi editor to create ordinary files on any Unix system. You simply need to give the
following command −

$ vi filename

The above command will open a file with the given filename. Now, press the key i to come into the edit
mode. Once you are in the edit mode, you can start writing your content in the file as in the following
program −

This is unix file....I created it for the first time.....


I'm going to save this content in this file.

Once you are done with the program, follow these steps −

● Press the key esc to come out of the edit mode.


● Press two keys Shift + ZZ together to come out of the file completely.

You will now have a file created with filename in the current directory.

$ vi filename
$

15
Editing Files
You can edit an existing file using the vi editor. We will discuss in short how to open an existing file −

$ vi filename

Once the file is opened, you can come in the edit mode by pressing the key i and then you can proceed by
editing the file. If you want to move here and there inside a file, then first you need to come out of the edit
mode by pressing the key Esc. After this, you can use the following keys to move inside a file −

● l key to move to the right side.


● h key to move to the left side.
● k key to move upside in the file.
● j key to move downside in the file.

So using the above keys, you can position your cursor wherever you want to edit. Once you are
positioned, then you can use the i key to come in the edit mode. Once you are done with the editing in
your file, press Esc and finally two keys Shift + ZZ together to come out of the file completely.

Display Content of a File


You can use the cat command to see the content of a file. Following is a simple example to see the content
of the above created file −

$ cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
$

You can display the line numbers by using the -b option along with the cat command as follows −

$ cat -b filename
1 This is unix file....I created it for the first time.....
2 I'm going to save this content in this file.
$

Counting Words in a File


You can use the wc command to get a count of the total number of lines, words, and characters contained
in a file. Following is a simple example to see the information about the file created above −

$ wc filename
2 19 103 filename
$

Here is the detail of all the four columns −

● First Column − Represents the total number of lines in the file.


● Second Column − Represents the total number of words in the file.
● Third Column − Represents the total number of bytes in the file. This is the actual size of the file.
16
● Fourth Column − Represents the file name.

You can give multiple files and get information about those files at a time. Following is simple syntax −

$ wc filename1 filename2 filename3

Copying Files
To make a copy of a file use the cp command. The basic syntax of the command is −

$ cp source_file destination_file

Following is the example to create a copy of the existing file filename.

$ cp filename copyfile
$

You will now find one more file copyfile in your current directory. This file will exactly be the same as
the original file filename.

Renaming Files
To change the name of a file, use the mv command. Following is the basic syntax −

$ mv old_file new_file

The following program will rename the existing file filename to newfile.

$ mv filename newfile
$

The mv command will move the existing file completely into the new file. In this case, you will find only
newfile in your current directory.

Deleting Files
To delete an existing file, use the rm command. Following is the basic syntax −

$ rm filename

Caution − A file may contain useful information. It is always recommended to be careful while using this
Delete command. It is better to use the -i option along with rm command.

Following is the example which shows how to completely remove the existing file filename.

$ rm filename
$

Multiple files can be removed at a time with the command given below :
17
$ rm filename1 filename2 filename3
$

NAME

rm - remove files or directories

SYNOPSIS
rm [OPTION]... FILE...

DESCRIPTION

rm removes each specified file. By default, it does not remove directories.

If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --
recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the
response is not affirmative, the entire command is aborted.

Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or
the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the
response is not affirmative, the file is skipped.

OPTIONS

TAG DESCRIPTION
-f, --force ignore nonexistent files, never prompt.
-i prompt before every removal.
prompt once before removing more than three files, or when removing
-I recursively. Less intrusive than -i, while still giving protection against most
mistakes.
prompt according to WHEN: never, once (-I), or always (-i). Without WHEN,
--interactive[=WHEN]
prompt always.
when removing a hierarchy recursively, skip any directory that is on a file
--one-file-system
system different from that of the corresponding command line argument.
--no-preserve-root do not treat '/' specially.
--preserve-root do not remove '/' (default).
-r, -R, --recursive remove directories and their contents recursively.
-v, --verbose explain what is being done.
--help display this help and exit.
--version output version information and exit.

18
Wildcard Characters
The shell interprets these special characters, also known as wildcard characters, as a specific
pattern of characters. The shell then compares all the file names under the directory specified in the
command to locate file names that match the pattern. The command is executed on files whose names
match the pattern.

Character Purpose
* Matches none or one character or a string of characters.
? Matches exactly one character.
[] Matches exactly one of a specified set of characters.

The * Wildcard

The shell interprets the *wildcard as a string of none, one or more characters.

[Steve@localhost Steve] $ cat c*

Here, c* will match the files whose name start with c.

The ? Wildcard

The shell interprets the ? wildcard as a string of exactly one occurrence of any character.

[Steve@localhost Steve] $ ls *.?

The above command displays all the files that contain any character(s) before a period, followed by a
single character after a period.

The [ ] Wildcard

The [ ] wildcard can be used to restrict the characters to be matched.

[Steve@localhost Steve] $ cat a[123]

The above command displays the contents of files with two character file names starting with a and with
the next character as 1, 2 or 3 such as a1, a2 and a3.

EXAMPLES

Example-1:

Remove the file myfile.txt. If the file is write-protected, you will be prompted to confirm that you really
want to delete it:
19
$ rm myfile.txt

Example-2:

Remove the file myfile.txt. You will not be prompted, even if the file is write-protected; if rm can delete
the file, it will:

$ rm -f myfile.txt

Example-3:

Remove all files in the working directory. If it is write-protected, you will be prompted before rm removes
it:

$ rm *

Example-4:

Remove all files in the working directory. rm will not prompt you for any reason before deleting them:

$ rm -f *

Example-5:

Attempt to remove every file in the working directory, but prompt before each file to confirm:

$ rm -i *

Example-6:

Remove every file in the working directory; prompt for confirmation if more than three files are being
deleted:

$ rm -I *

Example-7:

Remove the directory mydirectory, and any files and directories it contains. If a file or directory that rm
tries to delete
is write-protected, you will be prompted to make sure that you really want to delete it:

$ rm -r mydirectory

Example-8:

Same as the above command, but you will never be prompted; if rm can delete the files, it will:

$ rm -rf mydirectory

20
UNIT – III

CREATING FILES USING THE vi EDITOR


TEXT EDITORS
A text editor is a program that enables to create and modify text files. Typically, a text editor
provides a screen with a fixed line length and line numbers.
A text editor is usually less preferred by users over a word processor because a word processor
offers additional features, such as text formatting. A text editor can be used for:
● Create and edit documents.
● Create programs and utilities.
● Write e-mail messages.
Functions of a text editor
A text editor enables to perform the following functions:
● Create files: A text editor can be used to create, edit, and save files.
● Open files: A text editor can be used to open, modify and save an existing file. It is also used to
open multiple documents at a time.
● Copy text: text editors facilitate document creation because they enable to copy and paste text.
● Search for text: A text editor can be used to search a particular expression or a word. The search
and replace feature enables to change multiple instances of a particular word or a string.
Editors available with linux
Each operating system includes a text editor. There are various editors available with linux. Some
features that distinguish various editors are interactivity, online help, and the speed of operations. Some of
the various editors available in Linux are:
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 to control the system by using the keyboard. The vi
editor is commonly used to enter and edit source code and write short notes, such as e-mail messages.
The vim Editor
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.
21
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. The emacs editor is used 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 screen.
The ed Editor
The line editor or ed is used to create, display, modify and save text files. When we start the ed
editor with a file name as an argument, a copy of the file is created in the editor’s buffer. We can make
changes only to the copy of the file and not directly to file. To save the changes to a file, use the w
command.
The red Editor
The restricted editor or red is used to edit files in the current directory. This editor cannot execute
shell commands.
The joe Editor
Another popular editor available is the Joe’s own editor or joe. The joe editor is a full – screen
editor that lets to 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. It is used to send and receive e-mail messages. The pico editor offers various
features, including paragraph justification and search features. The pico editor provides a spelling checker
and a file browser, commands are displayed at the bottom of the screen.
THE vi EDITOR
The vi editor is a visual editor used to create and edit text files, documents, and programs. It
displays the contents of files on the screen. The vi editor is one of the oldest editors available for the
UNIX platform. The vi editor is available for all of the variants of UNIX and Linux.
Getting started with the vi Editor
Give the following command at the Linux prompt to invoke the vi editor:
vi filename <Enter>

22
The following table lists out the basic commands to use the vi editor −

S.No. Command & Description

1 vi filename
Creates a new file if it already does not exist, otherwise opens an
existing file.

2 vi -R filename
Opens an existing file in the read-only mode.

3 view filename
Opens an existing file in the read-only mode.

Following is an example to create a new file testfile if it already does not exist in the current working
directory −
$vi testfile

The above command will generate the following output −


|
~
~
~
~
~
~
~
~
~
~
~
~
"testfile" [New File]

A tilde (~) represents an unused line. If a line does not begin with a tilde and appears to be blank,
there is a space, tab, newline, or some other non-viewable character present.
The vi editor works in two modes, edit and command. The edit mode is used to add text to a file.
The vi editor has different commands to add, change, and delete text.

23
The command mode is used to move the cursor, save the file, and give various commands to
manage files.
To switch from edit mode to the command mode, press the <Esc> key. To switch from the
command mode to the edit mode, press a, A, o, O, i, or I keys.

Commands used in the vi Editor


The vi editor offers commands used for creating and editing files. The functions of various
commands used in the vi editor are:

S.No. Command & Description

1 k Moves the cursor to the line above the current line.

2 j Moves the cursor to the line below the current line.

3 h Moves the cursor to the pervious character .

4 l Moves the cursor to the next character .

5 x Deletes the character at the current cursor position.

6 :wq<Enter> Saves all changes and quits the vi editor.

7 :w<Enter> Saves the file.

8 :q!<Enter> Quits without saving changes.

9 :e<filename><Enter> Opens the specified file.

10 :r<filename><Enter> Reads and inserts the contents of the file after the
current line.

11 :w<filename><Enter> Writes to the specified file.

12 :w!<filename><Enter> Forcefully writes to the specified file.

13 :!<filename><Enter> Executes a shell command

24
Insert and Replace Commands
The following table describes the commands used to insert and replace text in the vi editor:

S.No. Command & Description

1 i Inserts text before the current cursor location

2 I Inserts text at the beginning of the current line

3 a Inserts text after the current cursor location

4 A Inserts text at the end of the current line

5 o Creates a new line for text entry below the cursor location

6 O Creates a new line for text entry above the cursor location

7 rx Replaces the current character with the specified character

8 Rtext<Esc> Replaces characters at the current cursor position with the


specified text, until the <Esc> key is pressed.

Cursor Movement Commands in the vi Editor


The basic cursor – movement command are:

S.No. Command & Description

1 <ctrl>d or D Scrolls down half screen

2 <ctrl>u or U Scrolls up half screen

3 <ctrl>F Moves a page forward

4 <ctrl>B Moves a page backward

5 0 (zero) Moves the cursor to the beginning of the line

6 $ Moves the cursor to the end of the line.

25
Word Movement Commands
The word movement commands are:

S.No. Command & Description

1 e Moves the cursor to the end of the word.

2 w Moves the cursor to the next word.

3 b Moves the cursor to the pervious word.

Deletion and modification Commands


The commands used for deleting and modifying text are:

S.No. Command & Description

1 dw Deletes a word.

2 dd Deletes a line.

3 cw Changes a word.

4 cc Changes a line.

5 X Deletes the character before the current cursor position.

6 J Join lines.

7 u Undoes the last change made.

8 .(dot) Repeats the last change made.

Commands to Copy Lines


The commands used to copy lines are:

S.No. Command & Description

26
1 yy or Y Yanks the current line, which is to be copied.

2 Nyy or NY Yanks N lines, including the current line.

3 p Places the yanked text after the current line.

4 P Places the yanked text before the current line.

To copy 20 lines of text from a file, give the 20yy command. The 20yy command will copy 20
lines of text starting from the current line.
Pattern – Finding Commands
The pattern – finding commands in the vi editor are:

S.No. Command & Description

1 fx Finds the specified character, x, on the current line after the current
cursor position.

2 Fx Finds the specified character, x, on the current line before the


current cursor position.

3 /pattern<Enter> Finds the next line containing the specified pattern.

4 ?pattern<Enter> Finds the pervious line containing the specified


pattern.

Managing Documents
Locating Files in Linux
The find Command
The find command is used to locate a file in a specific directory and all in its subdirectories.
Syntax
find [path] [expression]
The find command, specify the path where the files are located. The expression consists of options that
affect the execution of the find command. Some of the options of the find command are:
The –name Option
The –name option to specify the name of the files that to be located.

27
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 located. The
–name “jan” option specifies that all the files with the name jan are to be located.

root

bin usr home tmp

Steve

2000 2001 Desktop progs

d J f t d J f t t
a e e a e e e
f n b m f n b m m
p p p

A Sample Directory Structure


When the find command is used without the –name option, the command displays the path names
of all the files in the specified directory and its subdirectories.
Example: $ find / home / Steve
/ home / Steve / 2000
/ home / Steve / 2000 / df
/ home / Steve / 2000 / jan
/ home / Steve / 2000 / feb
/ home / Steve / 2000 / temp
.
.
28
/ home / Steve / progs / report

The –type Option


The –type option is used to locate a specific type of file.
Example : $ find / home / Steve –type f
The option f with –type searches for all the ordinary files.
$ find / home / Steve –type d
The option d with –type searches for all the directory files .

The –exec Option


The –exec option is used to specify the operations that need to be performed on the files that have
been located by the find command.
To remove all the files that are named temp from all the directories under a specific directory. The
following command is used:
$ find . –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.
The find command replaces the {} with the path names of the files, which are located by the
command, and each file is removed. The backslash followed by a semicolon at the end of the –exec option
is to specify the end of the command.
The –ok Option
The –exec option is to execute a command on each file located by the find command. The –ok
option is used to operate on files that are located. When the –ok option is used, the command prompts the
user for a confirmation before executing the command for each file.
The syntax of the –ok option is similar to that of the –exec option.
Example:
$ find . –name temp –type f –ok rm {} \;
To locate the file dmesg, the following command is used:
$ find / –name dmesg
To view the contents of the file, the following command is used:
$ find / –name dmesg –exec cat {} \;

29
Standard Files
Standard output
Utility

Standard error

Standard Input

A computer system consists of mainly three parts, input, processing, and output devices. The input
device accepts data from a user, and the output device displays or prints information or any error messages
that are generated. The processing device processes the user input according to the specified instructions
to generate the desired output.
The keyboard and mouse are examples of input devices, and the screen and the printer are the
examples of output devices. The CPU is the processing device.
In the Linux operating system, all input and output devices are considered special files.
Standard Input File
In Linux, the input is used to execute a command; the shell interprets the command and assigns the
keyboard as the default source of input. The keyboard is referred to as the standard input file.
If we specify the cat command with a file name, all the lines in the file are displayed. However,
without a file name, the cat command takes input from the standard input file or the keyboard as given
below:
$ cat <Enter>
The cat command waits for input from the keyboard. The screen will display the following output:
$ cat <Enter>
This is a test to depict <Enter>
This is a test to depict
While using the cat command, we can enter multiple lines. To indicate the end of input, press <Ctrl> and
d keys. The $ prompt is then displayed on the screen.
In Linux, all the open files, including standard files, are assigned a number called the file descriptor. The
standard input file is assigned the file descriptor 0.
Standard Output File
The shell assigns the screen as the default destination for the output of any command that is
executed. The screen is referred to as the standard output file.
Example:
$ ls
The shell executes the command and sends the output, the directory list, to the standard output file or the
screen. The standard output file is assigned the file descriptor 1.
Standard Error File

30
When a user types invalid or unauthorized commands, such as commands for which a user does
not have permission, the shell utilities display error messages on the screen. The screen is referred to as
the standard error file. This is assigned to the file descriptor 2.
Execute the cat command by a file name that does not exist, an error message is displayed on the
screen.
Error messages are displayed on the standard error file if you do not have appropriate permissions
on a file.
A user logs on to the Linux server and types the following command:
$ cp file1 dir1
The command is correct; it might generate error if the user does not have the write permission on
dir1 or the read permission on file1.
Redirection
The process of changing the assignment for the standard input, the standard output and the
standard error file is known as redirection.
Using redirection, input to a command can be taken from a file instead of the keyboard. Similarly,
the output of a command or error can be written to a file or printed instead of being displayed on the
screen. The three types of redirection are:
● Input
● Output
● Error
Input Redirection
The symbol for redirecting the input is <. We can redirect the input from a file instead of typing
the commands by using the keyboard.
Example
$ cat < test1 <Enter>
The < symbol implies input redirection from the file test1 on the hard disk. The cat command reads each
line of the file test1 as input and displays it on the screen. By specifying the input redirection, the standard
input is received from a disk file instead of the standard input file. The file descriptor can be using for the
above command as:
$ cat 0 < test1 <Enter>
Here, 0 indicates input redirection.
Output Redirection
The symbol for redirecting the input is >. To store the output of the ls command in another file instead of
displaying the output on the screen, you need to redirect the output to a file.
Example
$ cat test1 > test2
31
The > symbol implies redirection of the output to the file test2. The output of the cat command is
written to a disk file test2.
In output redirection, the file to which the output is redirected is first created on the disk as an
empty file before the output is sent to the file. However, if the file exists, its contents are deleted before
the output is written to it.
To add the output of a command at the end of a file instead of overwriting the existing contents of
the file. To append the output to the file test2, the following command is used:
$ cat test1 >> test2
The file descriptor can be used as follows:
$ cat test1 1> test2 and
$ cat test1 1>> test2
Here,1> indicates output redirection. Although the file descriptor 1 is not necessary, can include it in the
command for clarity.
Error Redirection
The following example explains error redirection:
$ cat datafile 2> error-msg <Enter>
Assume that the file datafile does not exist in the current directory. When a user tries to execute
the above command, Linux generates an error message because the execution is unsuccessful. In this case,
the error message will not be displayed on the screen (the standard error file); instead the message will be
written to the file error-msg.
Just like output redirection, error redirection first creates the file to which the error messages are
redirected and then writes the error output to the file.
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, such as cat, grep, wc, tr, and cut, to enable to
work effectively with data.
The grep Filter
The grep filter searches a file for a specified pattern of characters and displays all the lines that
contain the pattern. The pattern that is searched for is referred to as a regular expression. The grep filter
cannot be used without specifying a regular expression.
Syntax:
grep regular_expression [filename]

32
The filename is optional in the grep command. If we do not specify a file name, the grep filter excepts
input from the standard input file. While typing text, grep searches the line for the regular expression and
displays the line if it contains the specified expression. To stop the execution of the grep filter, press the
<Ctrl> and d keys.
Example:
$ grep job <Enter>
work
job
job
task
<Ctrl> d
In this example, the grep filter waits for input from the standard input file. The grep filter searches
for the word job when you enter the words work, job and task. When the grep filter locates the word job, it
displays the word job again on the standard output file. Notice that the word job appears two times in the
output.
Character Use Example Description
[ ] Matches any one of a set grep “New[abc]” Specifies the search pattern as
of characters. filename ‘Newa’, ’Newb’, or ‘Newc’.
[ ] with Matches any one of a grep “New[a-c]” Specifies the search pattern as
hyphen range of characters. filename ‘Newa’, ’Newb’, or ‘Newc’.
^ Matches the pattern grep Specifies the search pattern as
following it if the pattern “^New[abc]” ‘Newa’, ’Newb’, or ‘Newc’
occurs at the beginning of filename where the patter must occur at the
a line. beginning of a line.
^ within [ ] Matches the pattern that grep “New[^a- Specifies a pattern containing the
does not contain any c]” filename word ‘New’ followed by any
character in the specified character other than ‘a’, ‘b’, or
set. ‘c’.
$ Matches the pattern grep Specifies the search pattern as
preceding it if the pattern “New[abc]$” ‘Newa’, ’Newb’, or ‘Newc’
occurs at the end of each filename where the patter must occur at the
line. end of a line.

33
(dot) Matches any one grep Specifies a pattern containing the
character. “New.[abc]” word ‘New’ followed by any
filename character, followed by ‘a’, ‘b’, or
‘c’.
\ Ignores the special grep Specifies the search pattern, as
(backslash) meaning of the “New\.\[abc\]” New.[abc].The special meaning
filename of the dot, the opening bracket,
and closing bracket is ignored.
Options of the grep Filter
The grep filter offers options that enable to alter the output of the command. The options available with
the grep filter are as follows:
● -n : this option is used with the grep filter to display each line matching the specified pattern, along
with the line number. The line number is printed at the beginning of the line.
● -c : this option is used to display only a count of the lines that match the specified pattern.
● -v : this option is used to display all the lines that do not match the specified pattern.
The options are specified before the regular expression.
The wc Filter
The wc filter is used to count the number of lines, words, and characters in a file. It is also used in
standard input file.
Syntax
wc [ - lwc] [filename/s ]
Example
$ wc sample <Enter>
2 7 29 sample
The file sample has 2 lines, 7 words, and 29 characters.
The following table explains the options of the wc filter:

Option Function

-l Displays the number of lines.

-w Displays the number of words.

-c Displays the number of characters.

34
Similar to the grep filter, might or might not specify the filename with the wc filter. If do not specify a file
name with the wc filter, it excepts input from the standard input file, as shown below:
$ wc <Enter>
Wc is a filter
<Press Enter>
<Press Ctrl and d>
1 4 15
After typing the text, wc is a filter, and press the enter key, the wc filter counts the number lines, words,
and characters that have entered. The wc filter displays the number of lines, words, and characters entered
when the execution stops. As in the case of the grep filter, use the <Ctrl> and d keys to stop the execution
of the wc filter.
The cut Filter
The cut filter is used to extract specific columns from files. In addition, the cut filter is also used to extract
the output of certain commands, such as ls and who.
Syntax
cut [options] [filename/s]
The following table explains the options of the cut filter:

Option Function

-f<column_number(s)> Displays the specified columns.

-c<character_number(s)> Displays the specified characters.

-d<column_delimiter> Displays the column delimiter.

Examples
$ cut –d ‘ : ‘ –f1 / etc / passwd
Root
Bin
Daemon
Adm
Lp
Sync

35
In the above example, the cut filter is used to extract only the names of the users in the / etc/ passwd file.
The field separator is the : symbol.
The tr Filter
The tr filter is used to replace one set of characters with another.
Example
$ tr ‘ : ‘ ‘ ‘ < / etc / passwd
The above command replaces each occurrence of the : symbol in the / etc / passwd with a space and
displays the output on the standard output file. It is also used to replace repeated occurrences of a
character with a single occurrence of the character.
The –s option of the tr filter to squeeze several occurrences of a character into one character.
$ who > temporary
$ tr –s “ “ < temporary
root tty1 Sep 28 17:02
steve pts/4 Sep 28 19:36 (172.17.55.167)
In the above example, the –s option of the tr filter works on each record and reduces multiple spaces with
a single space.
The tr filter is used to change the casting of letters.
Example
$ tr “ [a – z] “ “ [A – Z] “
The road was a ribbon of moonlight
THE ROAD WAS A RIBBON OF MOONLIGHT
The above command converts all lowercase letters to uppercase.
PIPES
In Linux, we can combine filters with other Linux commands, such as ls or more, so that the
standard output of one filter or command can be sent as standard input to another filter or command.
Example
$ ls > tempfile
$ more tempfile
Here, the ls command stores a list of the directories in the file tempfile. The tempfile file is then used as
input by the more command.
By using the Linux pipe feature, the above two steps can be combined and executed as a single command
without creating a temporary file, as shown below:

36
$ ls | more
The vertical bar ( | ) is the pipe character, which indicates that the output of the command typed before the
| is to be sent as input to the command typed after the |.
The pipe command can be used to perform complex tasks by combing the commands available in Linux.
When pipe command is used, specify multiple commands or filters. To understand how the pipe command
works, consider the example in the figure below:
Input Output
Is
more
numbers
sort -
Command1 Command2

(Gives the (Takes the input


output to from
command 2) command1)
To display the names of all the ordinary files in the current directory, the following command is used:
$ ls –l | grep “ ^-“ | tr -s “ “ | cut -d “ “ –f9
Output
a.out
program.cc
test
In the above command the output of the ls-l command is provided as input to the grep command.
The ls-l command displays a detailed list of the files in the current directory. The grep command extracts
all the ordinary files. This output is then given to the tr command, which replaces multiple spaces with a
single space. The cut command takes this as input and extracts the ninth field, which is the filename, and
displays the file name.
The tee Command
In Linux, the intermediate output in a pipe is not saved on the disk. However we need to redirect
the standard output of a command to another command or save the output on the disk.
The tee command is used to redirect the standard input and write it to standard output or to file(s).
if the file in which data is to be stored does not exist, the file is created by the operating system. If the file
exists, the contents of the file are overwritten. The –a option is used to append contents to an existing file.
Example:
$ cat temp | tee temp1 temp2

37
The above command displays the contents of the file temp on the screen and also writes to the files temp1
and temp2.
Example:
$ sort numbers | tee sort – numbers | more
In the above command, the file numbers is sorted, and the sorted data is redirected to the tee
command. The tee command creates the file sort – numbers, and stores the data in the file. The tee
command also redirects data as input to the more utility.
The following figure depicts how the tee command works:

sort tee
numbers

38
UNIT – IV

SECURING FILES IN LINUX


FILE ACCESS PERMISSIONS (FAPS)
In Linux, file access permissions (FAPS) help to secure files and folders. File access permissions
refer to the permissions associated with a file with respect to the following:
● The file owner

● The group owner

● Other users

The permissions that can be granted or revoked are symbolically represented by the letters r, w, and x and
are grouped together as rwx for different users in Linux.
The permissions for a file or a directory are:
r – Indicates the read permission. It can be represented by the number 4.
w – Indicates the write permission. It can be represented by the number 2.
x – Indicates the execute permission. It can be represented by the number 1.
Access type Denoted by Action permitted on a file Action permitted on a directory
Read r Allows displaying copy Allows to list the contents of the
and compiling the file. directory
Write w Allow to edit, rename and Allows creating new files and
move the file to another subdirectories within this
location. directory.
Execute x Allows executing the file Allows to move to the specified
with the read permission. directory using the cd command
Viewing File Access Permissions
The ls command is used to display the names of files. The –l option with the ls command ,the
command displays the names of files with the date and time of creation, size, user name, group name, and
access permissions for the file.
Example:
[localhost]$ ls -l
Total 21
-rw-rw-r- 1 Steve Steve 134 Sep 21 10:48 DEADJOE
drwxr-xr-x 5 Steve Steve 1024 Sep 20 23:30 Desktop
drwxrwxr-x 2 Steve Steve 1024 Sep 21 22:56 tennis

39
FAP
_ r w z r - - r - -

Type of File Owner Permissions Group Permissions Other users’ permissions

The first character indicated the type of file, such as an ordinary file, a hidden file, or a directory.
The next set of three characters display the read, write, and execute permissions, in that order, for the file
owner. The following three characters are the permissions for the group owner, and the last three are the
permissions for other users.
If the permission is available, r, w or x is displayed; else a hyphen is displayed.
For directories, need to interpret FAPs as follows:
The read permission allows a user to:
● List the contents of a directory.
The write permission allows a user to:
● Copy files to a directory.
● Remove files from a directory.
● Rename the files in a directory.
● Make a subdirectory.
● Remove a subdirectory from the directory.
● Move files to and from the directory.
The execute permission allows a user to:
● Change to a directory.
● Display a file in a directory.
● Copy a file from a directory.
Changing File Access Permissions
The access permissions can be modified by associated with a file or a directory by using the chmod
command. However, only the owner of a file can change the permissions associated with it.
The chmod command can be used to grant or revoke permissions for files and directories.

Permissions can be granted to the:


● File owner, represented by the letter u.
● Group owner, represented by the letter g.
● Other users, represented by the letter o.

40
The permissions for a file or directory indicate the actions that can be performed on the file or the
directory.
When using the chmod command, use the + sign to grant permissions, and the – sign to revoke
permissions.
The syntax for the chmod command is shown below:
chmod <mode> <filename>
The chmod command is to specify the mode (permission to a type of user) in the following ways:
● Symbolic – The permission and the user type are specified as symbols.
● Absolute – The permission is specified as a number.
The following command shows the use of the chmod command:
[localhost] $ chmod g+x trial.rpt
[localhost] $ chmod o-w cust.rpt
In the first example, the group owner is granted the permission to execute the file, trial.rpt. In the second
example, the permission to write to the cust.rpt file is revoked from other users.
Symbolic Mode
In the symbolic mode, the symbols are used to specify the permissions and the types of
users, such as file owner or others, to whom the permissions are to be granted or revoked.
The following table explains the symbolic representation of entities:

Symbol Meaning

u Owner of the file or directory.

g Members of the same group.

o All other users.

a All users.

To modify the permissions for a file, the file owner must specify:
● The type of user for whom the permission is to be modified.
● The type of permission that is to be modified.
● Whether the permission is to be granted or revoked.
● The name of the file for which the permission is to be modified.
Linux allows changing FAPs for a specific user type. Some examples that demonstrate the use of FAPs:
[localhost] $ ls -l x.c
41
-rw-rw-r- 1 Steve IRDTECH 50 Sep 22 21:01 x.c
[loclhost] $ chmod u+x x.c
Here, ‘u’ indicates the file owner, ‘+’ indicates that the permission is to be given, ‘x’ indicates the execute
permission, and ‘x.c’ represents the file name.
After the above command is executed, the FAP for the file x.c will be modified as follows:
[localhost] $ ls -l x.c
-rw-rw-r- 1 Steve IRDTECH 50 Sep 22 21:01 x.c
To remove the read permission from the group owner, type the following command:
[localhost] $ chmod g-r x.c
Here, ‘g’ indicates the group owner, and ‘-‘ indicates that the permission is to be removed.
Absolute Mode
In the absolute mode, a series of digits is used to represent the file permissions. Using
the absolute mode is more convenient than using the symbolic mode because you can specify different
permissions for all the types of users in one statement.
The following table explains the number that denotes each type of permission:

Number Permission

4 Read

2 Write

1 Execute

The figure below depicts a sample representation of absolute numbers:


User Group Others

Symbolic rwx rw- r--

Binary 111 110 100

4+2+1 4+2+0 4+0+0

Octal 7 6 4
Assign permissions by using the following command:
[localhost] $ chmod 664 - / * . txt
Here, the first octet is for the file owner, the second octet is for the group owner, and the third octet is for
other users.

42
The following explains some of the permissions that are allocated when specifying a particular absolute
mode with the chmod command:
chmod 644 file.htm

Set the permissions of file.htm to "owner can read and write; group can read only; others can read only".

chmod -R 755 myfiles

Recursively (-R) Change the permissions of the directory myfiles, and all folders and files it contains, to
mode 755: User can read, write, and execute; group members and other users can read and execute, but
cannot write.

chmod 755 file.cgi

Set the permissions of file.cgi to "read, write, and execute by owner" and "read and execute by the group
and everyone else".

chmod 666 file.txt

Set the permission of file.txt to "read and write by everyone.".

chmod 400 file - Read by owner


chmod 040 file - Read by group
chmod 004 file - Read by world

chmod 200 file - Write by owner


chmod 020 file - Write by group
chmod 002 file - Write by world

chmod 100 file - execute by owner


chmod 010 file - execute by group
chmod 001 file - execute by world
To combine these, just add the numbers together:
chmod 444 file - Allow read permission to owner and group and world
chmod 777 file - Allow everyone to read, write, and execute file
Mode Used with the Permission of the File Meaning
chmod Command after the Command
500 -r-x------- Assigns read and execute permissions to the file
owner.
611 -rw---x---x Assigns read and write permissions to the file
owner and execute permission to group owner and
other users.
400 -r----------- Assigns the read permission to the owner.
6 ---------rw- Assigns read and write permissions to
other users.

43
61 ------rw—x Assigns the execute permission to other
users and the read and write permissions
to group members.
741 -rwxr------x Assigns read, write and execute
permissions to the owner, only the read
permission to group users, and only the
execute permission to other users.
777 -rwxrwxrwx Assigns read, write and execute
permissions to the owner, group user and
other users.
The unmask Value
When you create a file, the unmask value and the mode value determine the initial file
permissions. The mode value indicates that all the users have read and write permissions for a file. By
default, the mode value is 666 for files and 777 for directories and executable files. To derive file access
permissions, the value of unmask is subtracted from the mode value.
By default, the unmask value is given as 002 for user and 022 for root user, which means that each
file that a user creates has a permission, 666 – 002 = 664 (rw-rw-r-).
The unmask value is specified in the /etc/profile file. The unmask command is used to print or
modify the unmask value of files and directories. To ensure that the default file access permissions are
same across the various sessions in Linux, the unmask command is stored in the .bash_profile file. When
a new Bash shell is created, the unmask command is executed automatically.
The syntax for the unmask command is:
unmask [ value ]
Here, value is an octal number of up to three digits. For example, if you specify a value 0f 77, the
unmask command is interpreted by the operating system as 077.
The following table depicts the effect on files that are created by using the various unmask values.
In the table, the unmask values are listed in decreasing order of security:
Value Used with the unmask Permission of the File Meaning
Command after the Command
066 -rw--------- Assigns read and write permission to a user and no
access for group or other users.
026 -rw-r-------- Assigns read and write permissions to a user; read
permissions to group and no access to other users.

44
006 -rw-rw------ Assigns read and write permissions to a user and group
but no access to other users.
022 -rw-r—r--- Assigns read and write permissions to a user, read
permissions to group; and read permission to other
users.

Automating Tasks Using Shell Scripts


Introduction
The Shell as a Command Interpreter
The shell is an intermediary program, which interprets the commands that are typed at the
command prompt. The shell translates the commands that are understood by the kernel. The shell acts as
an interface between the users and the kernel and eliminates the need for a programmer to communicate
directly with the kernel.
A unique feature of the Linux operating system is that all Linux commands exist as utilities. These
utilities are located in individual files in any of the system directories, such as /bin, /etc, or /usr/bin. The
shell enables a user to access all the other utilities and resources of the computer.
The process of command interpretation by the shell is as follows:
● When you log on, the shell displays the Linux prompt, indicating that it is ready to execute
commands.
● When you give a command, the shell perform the following tasks:
❖ Reads the command.
❖ Searches for and locates the file, which has the same name as the command,
in the directories containing utilities.
❖ Loads the appropriate utility into memory.
❖ Executes the utility.
After completing execution, the shell displays the prompt again, indicating that can enter the next
command.
The following figure depicts the process of command interpretation:

The shell displays


the prompt on the
screen

The shell waits for Enter a command 45


the command to
complete execution
The shell interprets
and executes the
command

If the shell cannot locate a file corresponding to the command that you enter, the shell displays an error
message and then display the $ sign.
Example:
[ localhost ] $ lst file1
Bash: lst : command not found
[ localhost ] $
The echo Command
The echo command is used to display the messages on the screen.
Example:
$ echo “This is an example of the echo command”
This is an example of the echo command
$
The echo command displays text enclosed between “ “ on the screen. By default, the echo command
displays the text and then places a newline character at the end of it. The newline character moves the
cursor to the next line after the text is displayed. To keep the cursor on the same line, use –n option with
the echo command.
Example:
$ echo –n “This will keep the cursor on the same line”
The $ sign is displayed on the same line as the output.
Executing a Shell Script
Shell scripts can be used to automate tasks. The shell can read the file in which the commands are
stored and execute them. Such a file is called a script file.
To create a script file, need to write commands in a text file by using a text editor, such as the vi
editor. After creating the script file, need to execute it. The following file named magic that need to be
executed:
# ! / bin / bash

46
echo “This is my first bash script “
In the magic file, the first line of the file informs the shell to execute the script file by using the bash shell.
The other shell such as sh,tcsh, or ksh can also be used as a execute shells scripts. While creating a script
file, the # and ! characters should be the first two characters of the script file followed by the interpreter
that should be used to execute the file.
The magic file can be executed in the following ways:
1. At the command prompt, type:
$ bash magic
If there is an error in the first line of the shell script when it is executed, an error message “No such file or
directory” will be displayed. To resolve the problem, type the whereis bash command to locate the path of
the bash program, and use the path in the shell script.
2. At the command prompt, type:
$ chmod u+x magic Change FAP
$ ./magic Execute the shell script
To execute a shell script directly at the $prompt, need to change the FAPs for the script file. When you
log on to Linux, you begin work in a copy of the shell, known as the login shell. This shell is a utility.
Therefore, you can create a shell by executing the shell command. For example, to execute the bash
command to create the bash shell. The new shell is known as the subshell or child shell of the current
shell.
When executing a shell script directly at the $prompt, the current shell creates a child shell to
execute a shell script. The creation of the child shell ensures that the script does not affect the current
shell. The shell script is passed to the child shell for execution. The child shell is terminated as soon as the
shell script completes execution.
Example:
The following file is named hello:
# ! / bin / ksh
echo “Hello”
echo “World”

Change FAPs for the script file using the following command:
$ chmod u+x hello
$ ./hello
Hello
47
World
In the above example, the first line specifies that the shell script should be interpreted by using the Korn
shell (ksh).
Inserting commands
Can include comment entries in a shell script by prefixing statements with the # symbol. When the
shell encounters the # symbol, it ignores text following the # symbol in a line.
Example
# ! / bin / bash
echo “Hello”
# This is a comment line. This would not display any output.
echo “World”
In this example, the third line is a comment. The comment will be ignored by shell and no output will be
displayed. In a shell script, can add comments about the structure and working of the shell script for future
reference.
Variables
Creating Variables
Variables can be created at any point of time by simply assigning a value. A variable can be
created without a value by leaving the right-hand side of the assignment operator (=) blank. The syntax for
creating a variable is:
<variable name> = <value>
If the value is assign to the variable contains delimiter, such as an embedded space, it should be enclose
the value within either single or double quotes.
Example :
Name = “John Lennon”
However, need not use the quotation marks if the value does not have any embedded spaces.
In shell scripts, cannot declare variables as integers or characters. All the variables in the Linux operating
system are treated as character strings.
Example:
Name=Paul
Ctr=1
In the above example, ctr does not contain a numeric variable. The ctr variable contains a character.
Therefore, the ctr variable contains the character “1” and not the number 1.

48
Referencing Variables
The $ symbol is used to refer to the contents of a variable. For example, to assign the value of one
variable to another, use the following command:
variable1 = $(variable2)
In the above example, the value of variable2 is assigned to variable1.
The braces are used to delimit the variable name. For example, consider a variable named today
that contains the value 20 and another variable named x. Assign the value 20th to variable x by
concatenating the value of the variable today with the string th. To concatenate the values, you will use the
following command:
$ x = $(today)th
Now, x would contain the value 20th.
Reading a Value into a Variable
To assign a value to a variable, the shell specifies a value by using the keyboard. Enter the value
into a variable during the execution of a shell by using the read command.
$ read fname
The read command can be used at the shell prompt but is usually used in shell scripts. On execution, the
read command waits to enter a value for the variable. Press the <Enter> key after entering a value, the
remaining part of the shell script, if any, is executed. The read command does not prompt you to enter
data, can use the echo command to display a prompt.
$ echo “Enter your name”
Enter your name
$ read myname
Angela
In the above example, when the echo command is executed, a message is displayed. However, after the
read myname command is executed, the operating system waits for input. Enter Angela and press the
<Enter> key. The value, Angela, is stored in the variable myname. To display the value of the myname
variable by using the following command:
$ echo $myname
Angela
To store the names and phone numbers, you need to accept customer details, use the echo command to
prompt the user to enter data, use the read command to accept the values from the user. Finally, to store
the details in a file by using the >> operator.
The following shell script is used to store data and to accept details of customers:
49
#!/bin/bash
echo “Enter the name of the customer.”
read name
echo “Enter the mobile phone number.”
read number
echo “$name:$number”>>customerdata
Execute the storedata shell script by using the following command:
$ bash storedata
Alternatively, can acquire execute permission for the shell script and execute it as follows:
$chmod +x storedata
$ ./storedata
Local and Global Shell Variables
When a variable is referenced, only the shell that created it is aware of the variable. When a new
shell is created, it is unaware of the variables created in the parent shell. The same variable name can be
given a different value without the parent shell knowing about it. Such a variable is called a local variable.
When you create a variable, it is accessible only in the shell in which you create it. The subshells
or the parent shell of the current shell cannot access the variables of the current shell.
The following example explains the concept of a local variable:
$ continent=Africa
$ echo “$continent”
Africa
$ sh Creates a child shell
$ echo “$continent”
There is no response
$ continent=Asia Gives a new value, Asia to continent
$ echo “$continent”
Asia
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$ echo “$continent”
Africa Parent is unaware of Asia
$ sh Creates another child shell
$ echo “$continent”
Continent does not have any value
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$-
It is necessary for the child shell to know about the variables of the parent shell. The bash shell offers the
export command that enables the child shell to access the variables of the parent shell. Any shell variable
given as an argument to the export command is passed on to all subsequent child shells. A variable that is

50
made available to all the child shells of a shell is known as an exported variable. Consider the following
commands:
$ continent=Africa
$ export continent
$ echo “$continent”
Africa
$ sh Creates a new child shell
$ echo “$continent”
Africa Child shell has the variable continent
$ continent=Asia Gives a new value to continent
$ echo “$continent”
Asia
Press <Ctrl> d
$ exit Displays exit and returns to the parent shell
$ echo “$continent”
Africa Parent shell continues to have the value Africa
$-
In the commands given above, the last two commands show that variables can be exported or
passed on to child shells, but the opposite is not possible. The export command creates a copy of the
variable name and values and passes the copy to a child shell. The child shell can modify the value of the
copy of the variable. When the child shell terminates, the copy of the variable also ceases to exist. The
export command is used to pass on a variable to child shells, the original variable remains unaffected.
The variables created in a shell are local to the shell. In other words, variables created in a shell are
available only in the shell in which to create variables. The export command is used to make a variable
global or accessible to child shells.
Environment Variables
In a multiuser operating system, such as Linux, each user works on a copy of the shell. Each shell
has a set of special variables called environment variables, which users can edit to configure the shell’s
environment. By changing the values of environment variables, a user can customize the environment.
Some examples of environment variables are HOME, PATH, PS1, PS2, LOGNAME, SHLVL, and SHELL.
The HOME Variable
In the Linux operating system, each user has an associated directory called the home directory.
When a user logs on, by default, the user is taken to the corresponding home directory. The location of the
home directory of a user is stored in the environment variable HOME. For example, if the home directory
for the user Roger is /home/Roger, then the variable HOME will contain this value.
Example :
$ echo $HOME
The PATH Variable
51
The PATH variable contains a list of colon-delimited path names of directories that are to be
searched for an executable program. For example, the following command specifies that the directories to
be searched for any executable or command are /usr/bin and /bin, in that order:
$PATH = /usr/bin:/bin
The Linux operating system does not search the current directory. Only the directories specified in the
PATH variable are searched. To search the current directory, specify the path of the current directory in
the PATH variable. To specify the current directory in PATH variable a period is used.
Example:
a. PATH = /bin: /usr / bin : . – Searches in the order : /bin, /usr / bin, and the current directory.
b. PATH= . : bin : /usr/bin – Searches in the order : the current directory, / bin and / usr / bin
c. PATH = /bin : . : /usr/bin - Searches in the order : /bin, the current directory and / usr / bin
While executing a file, the Linux operating system is searched in the order specified in the PATH variable.
The PS1 Variable
The PS1 or Prompt String 1 variable contains the shell prompt, the $ symbol. The shell prompt can
be changing by editing the value of the PS1 variable. The following command will change the shell
prompt to HELLO>:
$ PS1=”HELLO>” <Enter>
HELLO> New prompt
While changing the shell prompt, ensure that there are no spaces before and after the = symbol. Also,
enclose the new prompt within quotation marks. The predefined prompt strings can be used to specify the
value of the PS1 variable. For example, the \w string is used to display the current working directory.
Example:
$ PS1=’\w>’
~ >cd /usr/doc
/usr/doc >_
In the above example, after you change the value of the PS1 variable, the prompt displays the tilde (~)
symbol, denoting the HOME directory. In addition, the prompt changes when you change to another
directory.
The man bash command is used to refer the man pages for the bash shell and view the prompt strings of
the PS1 variable.
The PS2 Variable

52
The PS2 variable specifies that the value for the secondary prompt. By default, the secondary
prompt is the > symbol. The Linux operating system displays the secondary prompt when you type an
incomplete command on the command line.
Example
$ PS1=’$
>
>‘
$_
In the above example, the value of the PS1 variable is enclosed within quotation marks but the quotation
marks are not closed. As a result, the command is considered incomplete. The > prompt is displayed
because of the incomplete command.
The following command is used to change the PS2 prompt:
$ PS2=^
$ echo “This is incomplete
^ close the quotes
^”
The LOGNAME Variable
The user’s login name is stored in the LOGNAME variable.
Example:
$ echo “ $ {LOGNAME} “
You might or might not enclose the LOGNAME variable in quotation marks and braces. The following
command can be used:
$ echo $LOGNAME
The SHLVL Variable
The SHLVL variable contains the shell level that is currently working in. When working on Linux,
create new shells and forget the level of the shell in which the shell is working. In the situation , the
SHLVL environment variable is used to know the level of the shell in which the shell is working. In the
Linux operating system, the login shell is assigned the number 1. When you create a new shell, the value
of the variable SHLVL is incremented by one.
Example:
$ echo $SHLVL
1 This is the login shell.
$ sh Creates a new shell.
53
$ echo $SHLVL
2 You are working in the new shell.
$ exit Terminates the child shell.
exit
$ echo $SHLVL
Returns to the parent shell, which is the login shell in this case.

The SHELL Variable


The SHELL environment variable stores the default shell of the user. You can view the value of
the variable by using the following command:
$ echo $SHELL
/bin / bash
The env Command
The env command is used to view a list of all the exported environment variables and their
respective values. env is a shell command for Linux, Unix, and Unix-like operating systems. It can be
used to print a list of the current environment variables, or to run another program in a custom
environment without modifying the current one.

Description
If env is run without any options, it prints the variables of the current environment. Otherwise, env sets
each NAME to VALUE and executes COMMAND.
env syntax
env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]
Options
-i, --ignore-environment Start with an empty environment.
-0, --null End each output line with a 0 (null) byte rather than a newline.
-u, --unset=NAME Remove variable NAME from the environment.
--help Display a help message and exit.
--version Display version information and exit.
- Same as -i.
The following example is an output of the env command
$ env

54
HOME=/computerhope/public_html
PATH=/usr/local/bin:
LOGNAME=admin
HZ=100
TERM=vt1000
TZ=MST7MDT
SHELL=/bin/csh
MAIL=/var/mail/computerhope
_INIT_UTS_PLATFORM=SUNW,SPARCstation-10
_INIT_UTS_RELEASE=5.7
_INIT_UTS_SYSNAME=SunOS
_INIT_UTS_VERSION=Generic_106541-08
EDITOR=pico -t
OPENWINHOME=/usr/openwin
MANPATH=/usr/man:/usr/local/man:/usr/openwin/man
LD_LIBRARY_PATH=/usr/local/lib:/usr/openwin/lib
PAGER=more
Command Substitution
In addition to pipes, the command substitution is used to combine more than one command in a
command line. To display the date message on the screen:
The date is (output of the date command)
To do so, enter any of the following command:
echo “The date is ‘date’”
The command date is enclosed in single backward quotation marks or a grave accent. While executing the
command, the shell first replaces the enclosed command with the output of the command. Then, the shell
executes the entire command.
The following command would also display the same output:
echo “The date is $ (date)”
The shell replaces $ (date) with the output of the date command.
The expr Command
In most shells, we cannot declare variables as integers. All variables are treated as character
strings. Therefore, in the following declaration, the variable var1 contains the characters 2 and 5, and not
the number 25:
55
var1=25
However, in Linux, can perform arithmetic operations by using the expr command to simulate numeric
variables and evaluate arithmetic expressions. The output of the expr command is sent to the standard
output file.
Example:
$ expr 4 + 5
The command in the above example will display 9 on the screen, need to add a space on either side of the
+ operator.
Example:
$ a=5
$ b=4
$ expr $a + $b
9
The operators supported by expr command are +, -, *, and /. When the * operator is used, it should
be preceded by the backslash character. If you do not precede the * operator with the backslash character,
the shell interprets the * operator as a wildcard character.
The expr command does not support decimals. The following command will display 2 and not 2.5
because the numeric value after the decimal point is ignored:
$ expr 5 / 2
The following command will result in syntax error because the decimal point in 2.5 will be treated as a
period:
$ var1 = 2.5
$ expr $var + 5
Therefore, the expr command will treat the value of the variable var1 as numeric.
The output of the expr command is displayed on the standard output file. The output of the expr
command should be stored in a variable, by using command substitution. The following command will
assign the value 25 to the var1 variable:
$ var1 = 5
$ var1 = ‘expr $var1 + 20’
The use of the expr command is shown in the following code:
a = 10
b=5
a = ‘ expr $a – 7’
echo “ a is equal to $a”
56
a = ‘ expr $a \* $b’
echo “ a is equal to $a”
a = ‘ expr $a / 3’
echo “ a is equal to $a”
The output of the code given above will be as follows:
a is equal to 3
a is equal to 15
a is equal to 5

Arithmetic Expansion
To calculate the value of an expression, enclose the expression in $ ( ( …. ) ).
Syntax
$ ( ( expression) )
Example
$ echo $ ( ( 45 + 43 ) )
79
To calculate the sum of the numbers, 45 and 34, enclose the numbers in (( )) along with the + operator.
While enclosing the expression in (( …)), can also specify variables instead of numbers in the expression.
Example
$ a = 25
$ b = 56
$ echo $ ( ( a + b ) )
81

57
UNIT - V

CONDITIONAL EXECUTION IN SHELL SCRIPTS

While writing a shell script, there may be a situation when you need to adopt one path out of the
given two paths. So you need to make use of conditional statements that allow your program to make
correct decisions and perform the right actions.
Linux Shell supports conditional statements which are used to perform different actions based on
different conditions. We will now understand two decision-making statements here −
● The if...else statement
● The case...esac statement
The if...else statements
If else statements are useful decision-making statements which can be used to select an option from a
given set of options.
Linux Shell supports following forms of if…else statement:
● if...fi statement
● if...else...fi statement
● if...elif...else...fi statement
Most of the if statements check relations using relational operators discussed in the previous chapter.
if...fi statement:
The if...fi statement is the fundamental control statement that allows Shell to make decisions and execute
statements conditionally.

Syntax if [ expression ]
then
Statement(s) to be executed if expression is true
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are
executed. If the expression is false then no statement would be executed. Most of the times, comparison
operators are used for making decisions.
58
It is recommended to be careful with the spaces between braces and expression. No space produces a
syntax error.
If expression is a shell command, then it will be assumed true if it returns 0 after execution. If it is a
Boolean expression, then it would be true if it returns true.

Example
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
The fiabove script will generate the following result −
a is not equal to b
if [ $a != $b ]
if...else...fi
then :
echo "a is not equal to b"
The if...else...fi statement is the next form of control statement that allows Shell to execute statements in a
fi
controlled way and make the right choice.

Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are
executed. If the expression is false, then no statement will be executed.

Example

The above example can also be written using the if...else statement as follows −

#!/bin/sh

a=10
b=20 59

if [ $a == $b ]
then
Upon execution, you will receive the following result −
a is not equal to b
if...elif...else...fi statement :
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make
correct decision out of several conditions.

Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi

This code is just a series of if statements, where each if is part of the else clause of the previous statement.
Here statement(s) are executed based on the true condition, if none of the condition is true then else block
is executed.

Example
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
60
elif [ $a -lt $b ]
then
echo "a is less than b"
else
Upon execution, you will receive the following result −
a is less than b

The case...esac Statement


You can use multiple if...elif statements to perform a multiway branch. However, this is not always the
best solution, especially when all of the branches depend on the value of a single variable.
Linux Shell supports case...esac statement which handles exactly this situation, and it does so more
efficiently than repeated if...elif statements.
There is only one form of case...esac statement which has been described in detail here −
● case...esac statement
The case...esac statement in the Linux shell is very similar to the switch...case statement we have in other
programming languages like C or C++ and PERL, etc.
Syntax
The basic syntax of the case...esac statement is to give an expression to evaluate and to execute several
different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.

case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac

61
Here the string word is compared against every pattern until a match is found. The statement(s) following
the matching pattern executes. If no matches are found, the case statement exits without performing any
action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump to the end
of the entire case statement. This is similar to break in the C programming language.
Example

#!/bin/sh

FRUIT="kiwi"

case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac

Upon execution, you will receive the following result −


New Zealand is famous for kiwi.
A good use for a case statement is the evaluation of command line arguments as follows −

#!/bin/sh

option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d
directory]"
exit 1 # Command to come out of the program
with status 1
;;
esac 62
Here is a sample run of the above program −

$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d Linux
Dir name is Linux
$
LOOPS IN LINUX
In this chapter, we will discuss shell loops in Linux. A loop is a powerful programming tool that enables
you to execute a set of commands repeatedly. In this chapter, we will examine the following types of
loops available to shell programmers −
● The while loop
● The for loop
● The until loop
● The select loop
You will use different loops based on the situation. For example, the while loop executes the given
commands until the given condition remains true; the until loop executes until a given condition becomes
true.
Once you have good programming practice you will gain the expertise and thereby, start using appropriate
loop based on the situation. Here, while and for loops are available in most of the other programming
languages like C, C++ and PERL, etc.
The while loop :
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is
usually used when you need to manipulate the value of a variable repeatedly.
Syntax

while command
do
Statement(s) to be executed if command is true 63
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are executed. If
command is false then no statement will be executed and the program will jump to the next line after the
done statement.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

Upon execution, you will receive the following result −


0
1
2
3
4
5
6
7
8
9
The for loop :
The for loop operates on lists of items. It repeats a set of commands for every item in a list.
Syntax

for var in word1 word2 ... wordN


do
Statement(s) to be executed for every word.
done

Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces
(words). Each time the for loop executes, the value of the variable var is set to the next word in the list of
words, word1 to wordN.
Example
Here is a simple example that uses the for loop to span through the given list of numbers −
#!/bin/sh 64

for var in 0 1 2 3 4 5 6 7 8 9
do
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9

The until loop :


The while loop is perfect for a situation where you need to execute a set of commands while some
condition is true. Sometimes you need to execute a set of commands until a condition is true.
Syntax

until command
do
Statement(s) to be executed until command is true
done

Here the Shell command is evaluated. If the resulting value is false, given statement(s) are executed. If the
command is true then no statement will be executed and the program jumps to the next line after the done
statement.
Example
Here is a simple example that uses the until loop to display the numbers zero to nine –

#!/bin/sh

a=0

until [ ! $a -lt 10 ]
do
echo $a
a = `expr $a + 1`
done 65
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9

The select loop :


The select loop provides an easy way to create a numbered menu from which users can select options. It is
useful when you need to ask the user to choose one or more items from a list of choices.

Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done

Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces
(words). Each time the for loop executes, the value of the variable var is set to the next word in the list of
words, word1 to wordN.
For every selection, a set of commands will be executed within the loop. This loop was introduced in ksh
and has been adapted into bash. It is not available in sh.
Example
Here is a simple example to let the user select a drink of choice −

#!/bin/ksh

select DRINK in tea cofee water juice appe all none


do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;; 66
none)
break
;;
The menu presented by the select loop looks like the following −
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
You can change the prompt displayed by the select loop by altering the variable PS3 as follows −
$PS3 = "Please make a selection => " ; export PS3
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$

Nesting Loops

All the loops support nesting concept which means you can put one loop inside another similar one or
different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming
requirement in a similar way −

Nesting while Loops

It is possible to use a while loop as part of the body of another while loop.

67
Syntax

while command1 ; # this is loop1, the outer loop


do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


done

Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you used
to count to nine –
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
This will produce the following result. It is important to note how echo -n works here. Here -n option lets
echo avoid printing a new line character.0
10
210
3210
43210
543210
6543210
76543210
876543210
9876543210
68
In this chapter, we will discuss shell loop control in Linux. So far you have looked at creating loops and
working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of
the loop.
In this chapter, we will learn following two statements that are used to control shell loops−
● The break statement
● The continue statement

The infinite Loop

All the loops have a limited life and they come out once the condition is false or true depending on the
loop.
A loop may continue forever if the required condition is not met. A loop that executes forever without
terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.

Example
Here is a simple example that uses the while loop to display the numbers zero to nine −

#!/bin/sh

a=10

until [ $a -lt 10 ]
do
echo $a
a=expr $a +forever
This loop continues 1` because a is always greater than or equal to 10 and it is never less than 10.
done
The break Statement

The break statement is used to terminate the execution of the entire loop, after completing the execution
of all of the lines of code up to the break statement. It then steps down to the code following the end of the
loop.

Syntax
The following break statement is used to come out of a loop −

The break command can also be used to exit from a nested loop using this format −
break n break
Here n specifies the nth enclosing loop to the exit from.

Example
Here is a simple example which shows that loop terminates as soon as a becomes 5 −
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
69
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and
var2 equals 0 −
#!/bin/sh

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
Upon execution, you will receive the following result. In the inner loop, you have a break command with
the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately
from the inner loop as well.
10
15

The continue statement

The continue statement is similar to the break command, except that it causes the current iteration of the
loop to exit, rather than the entire loop.
This statement is useful when an error has occurred but you want to try to execute the next iteration of the
loop.

Syntax
continue
Like with the break statement, an integer argument can be given to the continue command to skip
commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.

70
Example
The following loop makes use of the continue statement which returns from the continue statement and
starts processing the next statement −
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done

Upon execution, you will receive the following result −


Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number

SIMPLE PROGRAMS USING SHELL SCRIPTS

Hello World
Example 1. Hello World

#!/bin/sh
echo "Hello world"

Example 2. Shell Script Arguments

#!/bin/bash

# example of using arguments to a script


echo "My first name is $1"
echo "My surname is $2"
echo "Total number of arguments is $#"

Save this file as name.sh, set execute permission on that file by typing chmod a+x name.sh and then
execute the file like this: ./name.sh.
71
$ chmod a+x name.sh
$ ./name.sh Hans-Wolfgang Loidl
My first name is Hans-Wolfgang
My surname is Loidl
Total number of arguments is 2

72

You might also like