0% found this document useful (0 votes)
7 views

Unix Notes Bca

The document provides comprehensive notes on UNIX shell programming, detailing its history, features, file types, architecture, and commands. It discusses the evolution of UNIX from MULTICS to its variants, highlights its multitasking and multi-user capabilities, and explains the structure of the UNIX file system. Additionally, it covers different types of shells, system utilities, and various commands used in UNIX for file and directory management.

Uploaded by

Palak Jaiswal
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)
7 views

Unix Notes Bca

The document provides comprehensive notes on UNIX shell programming, detailing its history, features, file types, architecture, and commands. It discusses the evolution of UNIX from MULTICS to its variants, highlights its multitasking and multi-user capabilities, and explains the structure of the UNIX file system. Additionally, it covers different types of shells, system utilities, and various commands used in UNIX for file and directory management.

Uploaded by

Palak Jaiswal
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/ 91

lOMoARcPSD|25874097

Unix notes - Bca

Computer Science (Don Bosco Institute of Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Palak Jaiswal ([email protected])
lOMoARcPSD|25874097

UNIX SHELL PROGRAMMING


IV SEMESTER B.C.A

History of UNIX:

By 1960’s Massachusetts Institute of Technology (MIT), AT & T Bell Labs, and


General Electric came forward with a time sharing system called MULTICS
( MULTIPLEXED INFORMATION AND COMPUTING SYSTEM ).

By 1969, Ken Thompson , one of the member of AT & T Bell Labs felt MULTICS
is too complex , slow progress and had many problems so, he wrote first version of
UNIX as UNICS ( UNIPLEXED INFORMATION COMPUTING SYSTEM) in
Assembly Language.

In 1972, Ken Thompson and Dennis Ritchie rewrote the UNIX in C language to
achieve the portability.

AT&T made Unix available to universities and commercial firms, as well as the
United States government, under licenses.

There are various UNIX variants in the market like Solaris UNIX, AIX, HP UNIX
BSD etc.

Linux is the flavour of UNIX which is freely available.

Features of UNIX:
The features of UNIX are:
1. Multitasking:
A user can run multiple programs at the same time so UNIX is called as
Multasking .
2. Multi-user System:
Several users can use the UNIX System at the same time.so it is called as
Multiuser system.
3. Portability:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Unix is highly portable that can easily implemented on different hardware


platforms since it is written in C language.
4. Security:
UNIX provides security at various levels.
a. it provides security by assigning login name and password
b. File protection is provided by granting permissions ( read, write and execute )
c. UNIX supports File Encryption
4. Programming Facility:
UNIX Operating System also provides programming languages such as Shell
Programming and perl programming
5. Communication:
Communication can be established between users working on different terminals
connected to the network. The Users can easily exchange mails, data or programs
through network.
6. Pipes and Filters:
UNIX has facilities called Pipes and Filters which permit the user to create
complex programs from simple programs.
7.Utilities:
UNIX has over 200 utility programs for various functions. Utilities are powerful
tools that performs a special task . Some of the utilities are awk, grep, sed, cp etc.
8. UNIX shell:
UNIX has a simple user interface called the shell that has the power to provide the
services that the user wants.
9. Hierarchical File System:
UNIX uses a hierarchical file structure to store information. It allows for easy
maintenance and efficient implementation. Unix File System can be Local or
Distributed.
10.Machine-independence:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The System hides the machine architecture from the user, making it easier to write
applications that can run on micros, mins and mainframes.
11. Windowing System :
XWINDOWS is the first Graphical User Interface for UNIX. It supports network
applications and also can use multiple windows to run the programs

Types of Files in UNIX:


A File is a stream of bytes. ls -l command displays long listing of all files in
current directory
There are 3 types of Files in UNIX:
1. Ordinary or Regular Files ( - )
2. Directory Files ( d)
3. Device files ( b or c )
1. Ordinary files :
An ordinary file is a file on the system that contains data, text, or program
instructions.
Ordinary file can be a text file or binary file.
A text file contains only printable characters which user can view and edit them.
Example: all c programs , java programs and shell programs etc
A binary file contains both printable and non printable characters that covers entire
ASCII range.
Examples: all compiled c and java programs, video and sound files etc.

2. Directory Files:
A directory contains no data but keeps all details of the files and sub directories.
Directories store both special and ordinary files. A directory file contains an entry
for every file and subdirectory that it stores. Each entry has two components.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

(1) The Filename


(2) A unique identification number for the file or directory (called the inode
number)

3. Special Files : or device files


All devices files are stored in /dev directory. In Unix Files and Devices are treated
as same.
Special files are used to represent a real physical device such as a printer, tape
drive or terminal, used for Input/Output (I/O) operations.
They appear in a file system just like an ordinary file or a directory.

Unix File System:

Files in Unix System are organized into multi-level hierarchy structure known as a
directory tree. At the very top of the file system is a directory called “root” which
is represented by a “/”. All other files are “descendants” of root.

parent and child relationship structure:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

/:
The slash / denotes the root of the filesystem tree.
/bin :
The /bin directory contains certain fundamental utilities, such as ls or cp.
This is a directory where all commonly used unix commands are stored.
/sbin: or /usr/bin :
This directory stores all binary programs..There are some commands where user
cannot execute but System Administrator can execute. Such commands are
stored in this directory.
/etc :
This directory contains system configuration files and system databases. It also
contained maintenance utilities such as init. Login name and passwords etc.
/boot :
This directory contains all the files that are required for successful booting

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

process.
/dev :
This directory contains all device files such as fdsk, rdsk etc.
/home :
On many systems user files are stored in this directory. It contains the home
directories for the users.
/lib : or usr/lib:
This directory contains system libraries, and some critical files such as kernel
modules or device drivers.it also stores the required libraries and data files for
programs stored within /usr
/tmp:
This directory contains all temporary files
/mnt :
Stands for “mount”. contains filesystem mount points.
/proc :
This directory contains virtual filesystem showing information about processes
as files.
/root :
The home directory for the superuser “root” – that is, the system administrator.
/var :
This directory contains all user printing jobs and incoming and outgoing mails.
• /var/mail : This is the place where all the incoming mails and outgoing mails
are stored.
• /var/spool : Spool directory. Contains print jobs, mail spools and other
queued tasks.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Unix Architecture:

Kernel
The kernel is a part of the operating system. It interacts directly with the hardware
of the computer and manages all operations.
The main functions of the kernel are,

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

• Memory management
• process management
• Controlling access to the computer.
• Maintaining the file system.
• Handling interrupts.
• Handling errors.
• Performing input and output services.
• Allocate the resources of the computer among users.
The kernel is the main part of the Architecture of Unix OS.

The Shell
It is an interface between the kernel and the user. It reads the commands and then
interpret them and sends a request to execute a program. So, the shell is also called
a command interpreter.Users can interact with the shell using shell commands.

Shell is present in the /bin/sh directory. There are different types of shells. They are

1. Bourne Shell

2. C shell

3. Korn Shell

4. Bourne again Shell

Functions of shell:
1. File opening.
2.File writing.
3.Executing programs.
4.Obtaining detailed information about the program.
5.Termination of the process.
6. Getting information about time and date.

System Utilities:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

System Utilities are powerful tools that performs a special task.System Utilities
also includes System processes called Daemons.

System Utilities includes commands such as sed , awk , grep, ls etc.

Utility programs are software programs that add functionality to your computer or
help your computer perform better. These include antivirus, backup, disk repair,
file management, security, and networking programs.

Application Programs:

The applications and utility layer in Unix includes the word processors, graphics
programs, database management programs, commands etc.

The application programs provide an application to the end users. For example, a
web browser is used to find information while gaming software is used to play
games

File System:

UNIX File System includes hardware devices which can be a file, directory or sub
directory.These are the files that contain data, text and program instructions. Store
user information like an image drawn or some content written.UNIX files are local
or distributed.

Shell:
It is an interface between the kernel and the user. It reads the commands and then
interpret them and sends a request to execute a program. So, the shell is also called
a command interpreter.Users can interact with the shell using shell commands.

Types of shells:
There are mainly 4 shells namely
1. Bourne Shell (sh)
2. C shell (csh)

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

3. Korn Shell (ksh)


4. Bourne-again shell (bash)
1. Bourne Shell:
It is most popular shell used in UNIX System. It is the original UNIX Shell. It is
introduced by the author called Stephen Bourne at AT & T Bell Labs in 1977.The
source code is developed in C language. The executable filename of Bourne Shell
is sh. Default prompt is $
2. C Shell:
The C Shell was developed by Bill Joy at University of California in 1978. It is
similar to C language.C shell is not avialable in all machines.tc shell is a free
version of C shell. It include c type expression syntax and built in arithemetic.The
executable filename of C shell is csh.Default prompt is %.
3. Korn Shell:
Korn Shell was developed by David Korn in 1983 at AT & T Bell Labs. Korn Shell
combines the features of both bourne shell and c shell. It has c type array, functions
and string manipulating facilities.The executable filename of Korn Shell is
ksh.Default prompt is $
4. Bourne-again Shell:
The Bourne Shell was developed by Brain Fox in 1989.it is most widely used
shells today.It inherited all the features from Bourne Shell and Korn shell . This
shell supports piping, control statements,command substitution etc.The executable
filename of Bourne again shell is bash.Default prompt is $.

Different blocks of UNIX File System:


Every File System is organized into sequence of blocks. The size of each block is
1024 bytes
There are mainly 4 blocks in UNIX File System. They are
1. Boot block
2. super block

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

3. inode block
4. data block

Boot Block Super Block Inode Block Data Block

1. Boot block:
The Boot block contains bootstrap program that is used to load unix Operating
System.The bootstap program is stored in ROM.The bootstrap program gets
activated as soon as system is booted. The kernel is loaded into main memory
during the booting process.
2. Super Block:
The Super block contains the actual information of entire UNIX File System.It
maintains all free inode blocks and data blocks.
It contains the number of data blocks allocated.
It contains the number of free data blocks available.
It contains the number of free inode blocks available.
It contains the size of UNIX File System.
3.Inode block:
An inode is a datastructure in unix that contains information about a file within the
file systeem.
It contains the following information
1. attributes of the file
2. contains file permisions
3. contains the size of the file
4. date and time of last modification of the file.
$ ls -i prime.sh
4. data block:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The data block actually contains the content of a file.The address of data blocks are
available in linked list in the inode block.
There are 10 direct blocks and 3 indirect blocks.

Unix Commands:
Unix commands are inbuilt programs that can be invoked in multiple ways.
Unix has large set of commands.
Syntax:
$ command options filenames
Example:
$ ls -i fact.sh <enter>
5467 is inode number of fact.sh
$ls -i <enter>
prime.sh 2345 fact.sh 5467 programs 6789 even.sh 5677
$ ls <enter>
it lists all file and directories
$wc fact.sh <enter>
6 15 45 fact.sh
$ wc -l fact.sh<enter>
6

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

$ wc -w fact.sh <enter>
15
$ wc -c fact.sh<enter>
45
prime.sh fact.sh programs even.sh menu.sh unixprogs
features of unix command:
1.A unix command is a program that performs a specific task
2. All unix commands are written in lowercase letters only
3. Almost all unix commands are cryptic
Ex: cat for concatenation
wc for word count
4. options present in a command are indicated by hyphen symbol (-)
Types of commands in UNIX:
There are 2 types of commands in unix. They are
1. Internal commands
2. External commands
Internal commands:
The commands that are built into the shell are called internal commands.
Internal commands are executed directly by the shell.Internal commands will not
have a separate process. They will not find in PATH directory. All Internal
commands are also called as shell built in commands. The execution speed is high.
Example:
echo cd mkdir rmdir PATH etc.
External commands:
External commands are the commands that are executed by the kernel. These
commands will have a process id running for it. External Command existed in

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

any PATH directory like /bin, /usr/bin etc. like ls, sed, mv. These commands having
independent existence in /bin, /usr/bin, or any other directory. External commands
paths can be found using type command
Example:
ls sed cat who etc.

Directory related commands:


There are 4 directory related commands.They are
1. pwd ( present working directory)
2. cd (change directory)
3. mkdir( make or create directory)
4. rmdir (remove direcory)

1.pwd:
This command is used to display the path of current working directory.
$ pwd <enter>
/ home / raju
$ cd raj <enter>
$ pwd <enter>
/ home / raju/ raj
$ cd\ <enter>
$ pwd <enter>
/ home/raju

mkdir:
the mkdir command is used to create a directory.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

$mkdir labprgs
It will create a directory called labprgs
rmdir:
The rmdir is used to remove or to delete the directory
$rmdir labprgs
It will remove the directory labprgs
4. cd (change directory)
The cd commandis used to move from one directory to another directory
$ pwd <enter>
/ home / raju
$ cd raj <enter>
$pwd
/ home / raju / raj

File Related Commands:


1. cat (concatenation)
cat command is a filter.
Cat command is used
1. to create files
2. to display the contents of files
3. to concat files
4. to append files
1. Creating a file using cat command:
$ cat > file name <Enter>
--------------------

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

--------------------
--------------------
press <ctrl +d >
$

2. displaying a file content:


$ cat filename <Enter>
--------------
--------------
--------------
$
displaying multiple files:
$ cat file1 file2 file3 <enter>
file1
file2
file3
$
3. concatenating files
$ cat file1 file2 file3 > file4 <enter>
$ cat file4 <enter>
file1
file2
file3
$

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

4. appending files:
$ cat file1 >> file4 <enter>
$cat file4 <enter>
file4
file1
$

2.ls: (long listing)


The ls command is used to display the files, directories and subdirectories of
current working directory.
$ls <enter>
The ls command displays the files, directories and subdirectories of current
working directory alphabetically.
Options:
-r:
$ ls -r <enter>
The ls -r option is used to displays files and directories in reverse order or
descending order.
-i:
$ls -i <enter>
The ls -i option displays the inode number for all files and directories
-a:
$ls -a:
It displays all the files and directories including hidden files.
-l:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

$ls-l:
The ls -l option is used to display long listing of files
$ ls -l<enter>
-rw_rw_ r__ 1 raju student 48 2021.05.10 11:30:35 fact.sh
drw_rw_ r__ 1 raju student 148 2021.05.10 11:30:35 prgs
-F:
$ ls -F
It displays the directories with / which indicates they are directories.
3. wc: ( word count )
The wc command is used to count number of characters, words, lines in one or
more files.
Options:
there are 3 options with wc command.
-l: for counting lines
-w: for counting words
-c: for counting characters
$ wc fact.sh<enter>
6 12 45 fact.sh
$ wc -l fact.sh<enter>
6 fact.sh
$ wc -w fact.sh<enter>
12 fact.sh
$wc -c fact.sh<enter>
45 fact.sh
$ wc < fact.sh<enter>
6 12 45

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

4. head:
head cmd is used to display the top 10 lines of the file by default.
Ex:
$ head Filename <enter>
It displays first ten lines of the file filename by default.

$head -2 filename <enter>


It displays first 2 lines of the file filenames
$head -v filename <enter>
head with -v option displays first 10 lines along with filename as heading

5. tail
tail cmd is used to display the last 10 lines of the file by default.
Ex:
$ tail Filename <enter>
It displays last ten lines of the file filename.

$tail -2 filename <enter>


It displays last 2 lines of the file filenames
$tail -v filename <enter>
tail with -v option displays last 10 lines along with filename as heading

6.cp: (copy)
The cp command is used to copy a file or group of files.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The cp command needs atleast 2 arguements


Syntax:
$cp sourcefile newfile
when newfile doesnot exists, it will create and copies the contents of sourcefile to
newfile
if newfile is already existed,it will overwritten with the contents of sourcefile

Ex:
$cp file1 file2 <enter>
the contents of file1 will be copied to file2.

7. rm (remove)
The rm is used to remove or delete one or more files.
$rm file1 <enter>
it will delete the file file1
$rm f* <enter>
it will delete all the files starting with letter f.
$rm -r * <enter>
it removes all the files along with directories and subdirectories of current
directory
8.mv(move):
the mv command is used to move or rename files and directories.
It takes two arguements
it does two things
1. it renames a file or directory

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

2. moves set of files into a directory


$mv file1 file2 progs
it will move the files file1 and file2 into the directory progs

9. touch :
the touch command is used to create new empty files with zero bytes

$touch f1 f2 f3 f4
It will create empty files f1 f2 f3 and f4 with 0 bytes

wild cards or meta characters:


Meta characters are special characters to which special significance has been
given.
They are also called regular expressions or wild cards or pattern matching
The meta characters are
1. *
2. ?
3. [...] (clause)
4. [!...]
1. *:
‘*’ represents zero or more combination of any number of characters.
With command like ls, it displays complete list of filesystem
$ ls a* <enter>
if displays all files that begins with a letter ‘a’.
$ rm b* <enter>

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

It removes or deletes all files that begins with first letter ‘b’.
2. ?:
‘?’ represents any one character
$ls ?a?n <enter>
main rain pain
$ ls ???
aaa bbb
3. [...] :
it displays any one character from the enclosed list.
It indicates set of characters and will match a single character within the enclosed
list.
$ls chap[123] <enter>
chap1 chap2 chap3
$ls chap[abc]<enter>
chapa chapb chapc
$ls chap[a-z] <enter>
chapa chapb chapc chapg chapk chapm chapp chapr chapx chapz
4.[!...]
it displays any one character except those enclosed in the list.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Positional parameters:
The command line arguments can be accessed using $1,$2,$3,$4,$5,$6,$7,$8 and
$9
There are 9 positional parameters.They are
$1 to $9
The values of command line arguments are stored in special varaibles called
positional parameters.
First argument is stored $1 and second argument is strored in $2 and so on.
Set command:
set cmd is used to store the value of command line arguments into positional
parameters.
$ set Srinivas is studing 2nd bca in pims. He is from tumkur
$echo $1
Srinivas
$echo $9<enter>
He
$ shift 4
$ echo $1
bca
special parameters:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The special parameters are


1.$0
2. $#
3.$*
4.$?
5.$!
It holds the PID of last background job.
6.$$
it holds the PID of the current shell.
$0:
it holds the 0th parameter usually holds the name of the program.
$#:
it holds the total number of arguments that are passed at command line.
$*:
it holds the list of argumets
$?:
it returns the value zero when last command got executed successfully
otherwise it returns non-zero value.
Example:
$ vi para.sh
clear
echo “Program Name:$0”
echo “ Total no. Of argument are: $#”
echo “the arguments are: $*”
echo “First argument:$1

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “ second argument:$2”

Types of users in UNIX:


There are 3 types of users in UNIX. They are
1. user or owner (u)
2. group (g)
3. others (o)
1. user or owner (u):
A user is a owner of the file who created that file.
2. group(g):
A group contains multiple users.All users belonging to the group will have
permission access to the file.
3. others(o):
He is unauthorised user. He is not the user belongs to the group or created the file.
File Permissions or File Access Modes:
Every file or directory in unix has the following three permissions defined for 3
users.
The permissions for a file or directory can be listed using ls -l command.
The 3 file permissions are
1. read (r)
2. write(w)

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

3. execute(x)
read(r):
The read permission allows the user to view the contents of the file.
The read permission on directory will list the contents of a directory.
The octal value for read permission is 4.

write(w):
The write permission allows the userS to modify the contents of the file.
The write permission on directory allows user to edit (add or delete) the
Contents of a directory. The octal value for write permission is 2.
execute(x):
The execute permission allows user to execute or run the file.
The execute permission on directory allows users to access files or
subdirectories.The octal value for execute permission is 1.
Representation of file permissions:
There are 2 ways to represent file permissions. They are
1. Textual representation (rw-rw-r--)
2. Octal representation (664)
chmod command:
The chmod command allows user to set, add or delete the file permissions.
The chmod command is used in 2 ways
1. Symbolic mode or Textual representation
2. absolute mode or octal representation
1.Symbolic mode:
It is easiest way to modify the file or directory permissions.
Using this mode , user can add, delete or specify the permissions by using

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

operators
+ adds the permissions to the file or directory
- removes the permissions from a file or directory
= sets the designated permissions
2. absolute mode:
The absolute mode uses octal representation to set permissions.
Each permission is assigned a value.
Number octal permission reference
0 no permission ---
1 Execute Permission --x
2 Write Permission -w-
3 execute and write permissions -wx
4 read permission r--
5 read and execute permissions r-x
6 read and write permissions rw-
7 read,write and execute permissions rwx

Syntax of chmod command:


$ chmod category operation permissions filenames
The category can be
1. user or owner(u)
2. group (g)
3. others(o)
4. all (a)
The operations can be

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

+ adds the permissions


- removes the permissions
= sets the absolute permissions
The permissions can be
read (r)
write (w)
execute (x)
Examples on textual representation or symbolic mode
$ chmod ugo+x fact.sh <enter>
It assigns the execute permission to user, group and others.
$chmod go-w fact.sh <enter>
It removes the write permissions to group and others.
$chmod ugo=r fact.sh <enter>
It keeps the read permissions and removes other permissions.
$ chmod 777 fact.sh <enter>
It assigns read,write and execute permissions to all the users.
$ chmod 644 fact.sh <enter>
it allows read and write for user
and read permissions for group and others

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

pipe or piping (|):


pipe (|) sends output of one command as a input to another command
pipe (|) is used to establish the connection between two commands.
Complex tasks can be simplified by using pipe(|).
Pipe is an operator not a command
the output of the command on left hand side of pipe is used as a input to the
command on right hand side
Syntax:
command1 | command2 | command3 | --------- | command n
Example:
$ sort data.txt | uniq
it eleminates the duplicates entries in the file data.txt
$ cat names.txt | head -3 <enter>
It displays first 3 lines of the file names.txt
$cat names.txt | tail -4 <enter>
it displays last 4 lines of the file names.txt
$ cat names.txt | wc -l <enter>
It displays the total no of lines in number of the file names.taxt

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Filters:
Filters are set of commands that takes input from standard input, performs the
operation and sends the output to the standard output.
Filter is a small program that transforms plain data that can be used with other
filters and pipes to form a series of operations to produce the results.
The most common filters are:
1. cat
2. wc
3. head
4. tail
5. grep
6. tr
7. uniq
8. cut
9. paste
10. sort
Advanced Filters:
1. sed
2. awk

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

1. grep command:
grep stands for global regular expression print.
It is most popular filter.
Grep command filters the contents of the file that makes search easy.
It scans a file for occurrence of a pattern and displays the selected pattern.
grep command can also selects the lines not containing the pattern.
Syntax:
$ grep options pattern filenames
$ cat emp.lst <enter>
111 | Anil | Director | Sales | 25000
222 | Charan | director | production | 35000
333 | Siva | teacher | computers | 30000
444 | Shiva | Manager | Sales | 40000
555 | Kiran | Manager | production | 20000
$ grep “Sales” emp.lst <enter>
111 | Anil | Director | Sales | 25000
444 | Shiva | Manager | Sales | 40000
$ grep “teacher” emp.lst <enter>
333 | Siva | teacher | computers | 30000
options:
-c:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The -c option counts the occurrence of specific pattern


$ grep -c “Sales” emp.lst
2

-v:
The -v option is used to display all the lines except the lines containing the pattern.
$ grep -v “Sales” emp.lst <enter>
222 | Charan | director | production | 35000
333 | Siva | teacher | computers | 30000
555 | Kiran | Manager | production | 20000
-i:
It displays the output ignoring the case of the pattern. It treats uppercase and
lowercase letters same.
$ grep “director” emp.lst <enter>
222 | Charan | director | production | 35000
$ grep -i “director” emp.lst <enter>
111 | Anil | Director | Sales | 25000
222 | Charan | director | production | 35000
-e:
The -e option is used to search multiple patterns at a time.
$grep -e “Sales” -e “teacher” emp.lst <enter>
111 | Anil | Director | Sales | 25000
333 | Siva | teacher | computers | 30000
444 | Shiva | Manager | Sales | 40000
-l:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

It will list the filenames conataining the pattern

2. sort command:
sort command is used to sort the contents of a file either in ascending order or
descending order.
It is also used to merge two or more sorted files.
By default, sort command sorts the date in ASCII sequence.
That is,
whitespace
numeric data
uppercase letters
lowercase letters
options:
-r:
the -r option is used to sort the file in descending order
-d: (dictionary sort)
it is used sort the data according to the dictionary
whitespace
special characters
numeric data
uppercase letters
lowercase letters
-m: (merge)
the -m option is used to merge two or more sorted files

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

$sort -m file1 file2


-o:
it will sort the data and stores the result in a specified file.
$ sort -o outputfile inputfile
2. uniq:
uniq command is used to remove the duplicate entries.
It counts the number of duplicate entries
uniq command generates the output accurately with help of sort command
If there are any duplicate entries, it will filter and display only once
$ cat data.txt <enter>
anil
charan
kiran
anil
balaji
$ sort data.txt | uniq <enter>
anil
balaji
charan
kiran
options:
-c:
it counts the number of times the each entry is present

tr: translate:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

the tr command is used to replace the each character in a specified set of


characterswith corresponding characters in second set.

Cut command: it is a filter.


The cut command is used to extract one or more columns from either standard
input or from a file.
The cut command is similar to head and tail commands.
The cut command cuts the file vertically where as head and tail commands cuts
the file horizontally.
Syntax:
$ cut options filenames
options:
-c: cutting columns
the -c option extracts a specified column with a list of columns delimited by
comma.
Range can also be given by using hyphen (-)
$cut -c 1-3 emp.lst
It displays first 3 columns of the file emp.lst
$cut -c 1-3,7-12,35- emp.lst
it displays the specified columns from the file emp.lst
-f :cutting fields
The -f option is used to cut or extracts a specified field.
Fields are separated by delimiter |
Any character can be delimiter.
If no delimiter is specified, cut command assumes tab or space as delimiter
multiple fields are separated by command

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The delimiters are specified by using -d option


$ cut -d’|’ -f 1,3 emp.lst
it sdisplays sirst and 3rd fields from the file emp.lst
$ cut -d’|’ -f 3-5 emp.lst
it displays 3rd,4th and 5th fields from the file emp.lst
6.paste:
The paste command combines the files horizontally.
It combines the first line of file with first line of second file to the standard output.
Between columns, it writes a tab and at the end of the last column it writes a
newline
options:
There is only one option for paste command
-d:
The -d option is used to specify the delimiters to separate the data.
$

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

comparing files:
There are 3 unix commands for comparing the files.
1. cmp (compare)
2. diff(difference)
3. comm(common)
1. cmp:
the cmp command compares the files byte by byte.
The cmp command without any option stops at when first byte difference
is reported.
When files are identical, no message is displayed.
Syntax:
$cmp options file1 file2
Ex:
$cmp file1 file2
options:
-l:
the -l option is used to list all the differences found in the files byte by byte
$cmp -l file1 file2
2. diff:(differnce)
The diff command shows line by line differences between two files.
The differences are identified such that the first file can be modified making it to
match the second file.
$diff file1 file2 <enter>
2 c 2 (2-line to be changed of a file)
<789

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

>as9
3. comm:(common)
The comm command is used to find the identical data in two files.
It works on two sorted files.
It compares the files line by line and displays the results in 3 columns.
The first column contains the unique lines in file1
The second column contains the unique lines in file2
The third column contains the unique lines in both file1 and file2.
Syntax:
$comm options file1 file2
$ cat file1
agra
bangalore
chennai
$cat file2
bangalore
chennai
delhi
$comm file1 file2
agra bangalore
chennai
delhi

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Shell Programming
Shell:
Every Unix System consists of at least one shell.
Shell acts as an interface between user and kernel.
When user logs into the Unix System,a prompt called shell prompt appears on the
screen.
The shell prompt could be $,% or #
Types of shells:
The most popular shells in unix or linux sre
1. Bourne Shell (sh)
2. C shell (csh)
3. Korn Shell (ksh)
4. Bourne-again shell (bash)
1. Bourne Shell:
It is most popular shell used in UNIX System. It is the original UNIX Shell. It is
introduced by the author called Stephen Bourne at AT & T Bell Labs in 1977.The
source code is developed in C language. The executable filename of Bourne Shell
is sh. Default prompt is $
2. C Shell:
The C Shell was developed by Bill Joy at University of California in 1978. It is
similar to C language.C shell is not avialable in all machines.tc shell is a free
version of C shell. It include c type expression syntax and built in arithemetic.The
executable filename of C shell is csh.Default prompt is %.
3. Korn Shell:
Korn Shell was developed by David Korn in 1983 at AT & T Bell Labs. Korn Shell
combines the features of both bourne shell and c shell. It has c type array, functions
and string manipulating facilities.The executable filename of Korn Shell is

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

ksh.Default prompt is $
4. Bourne-again Shell:
The Bourne Shell was developed by Brain Fox in 1989.it is most widely used
shells today.It inherited all the features from Bourne Shell and Korn shell . This
shell supports piping, control statements,command substitution etc.The executable
filename of Bourne again shell is bash.Default prompt is $.
shell variables:
There are 3 shell variables
1.System variables or environmental variables
2. user defined variables or local variables
3. readonly vaiables or constants
1.System variables or environmental variables:
System variables should be written in UPPERCASE letters
they are predefined variables in the Syste,
ex: PATH, PS1, IFS,HOME,SHELL,LOGNAME
LOCAL VARIABLES:
THESE are the variables that are defined by the user. They will exist only during
the execution of the program.
Ex:
i=10
here i is called a local variable.
Readonly variables(constants)
the values of readonly variables are always fixed and does not change during the
execution of a program.
To define a constant in unix, the keyword ‘readonly’ is used.
x=100; #local variable
readonly x=100; #constant

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

x=`expr $x + 10` # error


Keywords:
keywords are the words whose meaning is already defined in the system.
Keywords cannot be used as shell variables.
Some of the keywords are
echo read readonly if in fi
until
while do done for case esac
break continue exit return shift set
unset
comments:
in shell programming , comments are defined using # character.
# character is the first character of the comment line
The comments will explain the purpose of the program, logic of the program.
# shell program to print prime numbers
echo:
echo is used to print the line of text or string or value of the variable on the
terminal.
echo is a built in command
by default, echo includes newline (\n) at the end of each string it prints.
Syntax:
$echo options strings
to print plain text,
$echo “string”
Ex:
$ echo “hello”

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

hello
to print values of the variables
$ echo $variable
Ex:
$i=10
$ echo $i
10
options:
-n:
The -n option is used to remove the newline (\n) from the output

-e:
The -e option is used to recognize the escape sequences like \t, \n, in the input
string.
read:
The read statement is used to accept the input and stores in a variable.
read is a built in command
Syntax:
$read variable1 variable2 variable3 ------variable n
Ex:
$ read a b c
# here a,b and c are variables
Example:
clear
echo “Enter any value:” 10
read a

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “The given value is $a”


expr:
The expr command is used evaluate the integer arithmetic expressions like
addition,subtraction,multiplication,division and modulus.
Expr command does not support floating point values.
To use floating values we use the ‘bc’ command
It is also used to evaluate the regular expressions,length of the strings etc.
Syntax:
$ expr expression
Ex:
addition
sum=`expr 10 + 20`
Ex:
to find length of a string
$x=”hello”
$len=`expr length $x`
$echo $len
5
to extract substring from given string
$x=”hello”
$sub=`expr substr $x 2 3`
$echo $sub
ell # extracts 3 characters from position 2

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

test command:
The test command in unix is used to evaluate the expression
test is a built in command that returns true(0) or false (1) depending on the
evaluation of the expression.
The test command is used to find the equality of strings or file check and compares
the values.
Syntax:
test expression
(or)
[expression]
Types of tests:
There are 3 tests in unix. They are
1. numeric test
2. string test
3. file test
1. numeric test:
The numeric test comprises of relational and logical operators.
Relational operators:
There are 6 relational operators. They are
operator meaning
-eq equals to
-ne not equals to
-lt less than
-le less than or equals to

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

-gt greater than


-ge greater than or equals to
logical operators:
There are 3 logical operators
operator meaning
-a logical and
-o logical or
! logical not
2. String test:
string tests are used to check for equality of two strings,length of a string, non
equality of two strings etc.
Operator meaning
str1 = str2 returns true (0) if str1 equals to str2
str1 != str2 returns true (0) if str1 not equals to str2
-n string returns true (0) if string is not null and exists
-z string returns true (0) if string is null and exists

Examples on String Test:


clear
str1=”Unix”
str2=”Linux”
str3 = “ “
str4=”Unix”
if [ $str1 = $str4 ]
then

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “$str1 and $str2 are equal”


else
echo “$str1 and $str2 are not equal”
fi
if [ $str2 != $str4 ]
then
echo “$str2 and $str4 are not equal”
fi
if [ -z $str3 ]
then
echo “$str3 is null and existed”
fi
if [ -n $str1 ]
then
echo “ $str1 is not null and existed”
fi
3. file test:
file test is used to to check the status of the file,directories and their file
permissions
operator meaning
-f file returns true if ‘file’ exists and is an ordinary file
-d file returns true if ‘file’ is a directory
-e file returns true if ‘file’ exists
-s file returns true if ‘file’ exists and is non empty file
-r file returns true if ‘file’ is readable

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

-w file return true if ‘file’ is writable


-x file returns true if ‘file’ is executable
Example:
clear
echo “Enter any filename:”
read fname
if [ -f $fname ]
then
echo “$fname is an ordinary file”
fi
if [ -d $fname ]
then
echo “$fname is an directory file”
fi

Control structures or Control Statements:


Control statements controls the flow of execution in the program.
There are 3 types of control statements. They are
1. sequential control statements
2. conditional control statements
3. unconditional control statements
1. sequential control statements:
These statements does not skip any program code and execute each and every
statement sequentially.
Each command or statement will execute in the order in which the commands are
listed.

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

Example:
# Shell Script to find sum of two numbers
clear
echo “Enter any two numbers:”
read a b
sum=`expr $a + $b`
echo “sum of $a and $b is: $sum`

2. conditional control statements:


The conditional control statements are used to make decision based on given
condition.
Conditional control statements are divided into 2 types. They are
a. Branching statements or decision making statements
b. looping statements

Branching statements: or Decision making statements or selection statements:


There are 5 branching statements. They are
1. if-then -fi statements
2. if-then-else-fi statement
3. if-then-elif-fi statement (else if ladder)
4. nested if statement
5. case-esac statement (switch statement)
1. simple if statement or if-then-fi statement:
Syntax:
if [ condition ]
then

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

commands or statements
fi
(or)
if [ condition ];then

commands or statements
fi
Example:
clear
echo “enter any number(1-100):” 50
read n
if [ $n -le 100 ]
then
echo “ given number is less than 100”
fi
if-then-else-fi statement:
Syntax:
if [ condition ]
then
commands or statements (true block)
else
commands or statements (false block)
fi
Example:01
clear
echo “Enter any number:” 20

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

read n
if [ $n -lt 0 ]
echo “$n is negative number”
else
echo “$n is positive number”
fi
Example:02
clear
echo “Enter your age:
read age
if [ $age -ge 18 ]
echo “ Eligible for voting”
else
echo “ not eligible for voting”
fi
Example :03:
clear
echo “Enter any year:” 2020
read year
r=`expr $year % 4`
if [ $r -eq 0 ]
then
echo “$year is a leap year”
else
echo “$year is not leap year”

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

fi
Example :04
clear
echo “Enter any 2 numbers:”
read a b
if [ $a -gt $b ]
then
echo “$a is large number”
else
echo “$b is large number”
fi
Example :05

# Shell program to find whether given number is even or odd


(part-B 1st program)
clear
echo “Enter any number:” n rem
read n 11 1
rem=`expr $n % 2`
if [ $rem -eq 0 ]
then
echo “$n is an Even Number”
else

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “$n is an Odd Number”


fi

3. if-then-elif-fi statement: or else if ladder


Syntax:
if [ condition1 ]
then
commands to execute if condition1 is true
elif [ condition2 ]
then
commands to execute if condition 2 is true
elif [ condition3 ]
then
commands to execute if condition3 is true

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

-
-
-
elif [ condition n ]
then
commands to execute if condition n is true
else
commands to execute if no condition is true
fi
Syntax :02
if [ condition1 ]
then
commands to execute if condition1 is true
else if [ condition2 ]
then
commands to execute if condition 2 is true
else if [ condition3 ]
then
commands to execute if condition3 is true
-
-
-
else if [ condition n ]
then
commands to execute if condition n is true

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

else
commands to execute if no condition is true
fi
fi
fi
fi
# shell program to find largest of 3 numbers (part B 2nd Program)
clear
echo “Enter any 3 numbers:”
read a b c
if [ $a -gt $b -a $a -gt $c ]
then
echo “$a is largest number”
elif [ $b -gt $a -a $b -gt $c ]
then
echo “$b is largest number”
else
echo “$c is largest number”
fi

# shell program to find minimum of 3 numbers


clear
echo “Enter any 3 numbers:”
read a b c
if [ $a -lt $b -a $a -lt $c ]

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

then
echo “$a is smallest number”
elif [ $b -lt $a -a $b -lt $c ]
then
echo “$b is smallest number”
else
echo “$c is smallest number”
fi

#Shell Program to find grade of a student using if-then-elif statement


(part B:3rd program)
clear
echo “Enter register number:”
read regno
echo “Enter student name:”
read name
echo “Enter marks for vb, OR,UNIX:”
read vb or unix

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

sum=`expr $vb + $or + $unix`


avg=`expr $sum / 3`
if [ $vb -lt 40 -o $or -lt 40 -o $unix -lt 40 ]
then
echo “Fail”
elif [ $avg -ge 75 ]
then
echo “Distinction”
elif [ $avg -ge 60 -a $avg -lt 75 ]
then
echo “First Class”
elif [ $avg -ge 50 -a $avg -lt 60 ]
then
echo “Second class”
else
echo “ Pass”
fi
nested if statement:
The process of defining the if or if else statement inside another if statement is
called nested if statement.
Syntax:
if [ condition1]
then
commands or statements
if [ condition2]
then

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

commands or statements
else
commands or statements
fi
else
commands or statements
fi

Example:
clear
echo “Enter username:”
read user
if [ $user = “abcd” ]
then
echo “Enter password:”
read ps
if [ $ps = “1234”]

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

then
echo “Hello $user”
else
echo “Wrong Password”
fi
else
echo “wrong username”
fi

case-esac statement:
It is similar to switch statement in C language.
It is used to select one choice among multiple choices.
Syntax:
case $variable in
value1) statements or commands
;;
value2) statements or commands
;;

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

-
-
-
value n) statements or commands
;;
*) default statements or commands
esac
statement x
Explanation:
The value of variable will match the case values,if match is found then the
statements or commands under that case value will be executed and transfers the
control to statement x
if the value of variable does not match any of the case values then
the statements or commands under default section *) will be executed.

Example:
clear
echo “Enter day value (1-7):” 3
read d
case $d in
1) echo “Monday”
;;
2) echo “Tuesday”
:;

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

3) echo “wednesday”
:;
4) echo “Thursday”
:;
5) echo “friday”
:;
6) echo “saturday”
:;
7) echo “sunday”
;;
*) echo “invalid choice”
esac
Example:02
clear
echo “Enter any alphabet”
read ch
case $ch in
[aeiouAEIOU]) echo “ $ch is a vowel”
;;
*) echo “$ch is a consonant”
esac
Example:03
clear
echo “Enter any character:” ^
read ch
case $ch in
[0-9]) echo “$ch is a digit”

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

;;
[a-zA-Z]) echo “$ch is an alphabet”
;;
?) echo “$ch is a special character”
;;
*) echo “invalid choice”
esac

Example:04 (partb 4 program)


clear
echo -e “\n1.Calender\n2.Date\n3.Listing files\n4.Present Working Directory\
n5.Exit\n”
echo “Enter your choice:”
read ch
case $ch in
1) cal ;;
2) date ;;
3) ls ;;

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

4) pwd ;;
5) exit ;;
*) echo “ invalid choice”
esac
looping statements or iteration statements:
The process of executing the one or more statements repeatedly until
some condition is satishfied.
There are 3 looping statements
1. while
2. until
3. for

while loop:
Syntax:
while [ condition ]
do
statements or commands
done
statement x
Explanation:
The statements or commands between do and done will be executed as long as

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

condition is true otherwise the control will transfer to statement x


Example 01:
clear
i=1 i
while [ $i -le 5 ] 1
do 2
echo “$i” 3
i=`expr $i + 1` 4
done 5
o/p: 6
1
2
3
4
5

2. until loop:
Syntax:
until [ condition ]
do
commands or statements
done
stateement x

Explanation:

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The statements or commands between do and done will be executed as long as the
condition is false. If condition is true, the control flow will transfer to the statement
x
Example:
clear i
i=1 1
until [ $i -gt 5] 2
do 3
echo $i 4
i=`expr $i + 1` 5
done 6
o/p:
1
2
3
4
5

3. for loop:
Syntax:
for variable in list
do
commands or statements
done
statement x
The for loop operates on list of items.It repeats set of commands or statements for

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

every item in the list.


The variable is the name which holds the item in the list.
Each time the for loop executes, the value of the variable is set to next word in the
list.
Example:
for i in 1 2 3 4 5
do
echo “$i”
done

# Shell program to find factorial of a number ( part a 1st program)


Ex: 4!=4X3X2X1=24
clear
echo “Enter any positive number:”
read n n i fact
i=1 4 1 1
fact=1 2 1
while [ $i -le $n ] 3 2
do 4 6
fact=`expr $fact \* $i` 5 24

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

i=`expr $i + 1`
done
echo “Factorial of $n is:$fact”
or
clear
echo “Enter any positive number:”
read n
num=$n num n fact
fact=1 4 4 1
while [ $n -ge 1] 3 4
do 2 12
fact=`expr $fact \* $n` 1 24
n=`expr $n – 1` 0 24
done
echo “factorial of $num is:$fact”

# Shell program to find reverse of a given number


# partb 5th program.
clear
rev=0 rem num n rev
echo “Enter any number:” 4 234 234 0
read n 3 23 4
num=$n 2 2 43
while [ $n -gt 0 ] 0 432
do

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

rem=`expr $n % 10`
rev=`expr $rev \* 10 + $rem`
n=`expr $n / 10`
done
echo “The reverse of $num is $rev

Jump statements: Unconditional Control Statements


The Jump Statements are
1. break
2. continue
break:
break statement is used to exit from any loop such as while, until
and for loop on certain condition. break statement is generally used with ‘if’
statement.

Syntax:
while [condition]
do
if [ condition ]
then
break;
fi
done

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

statement x
Example:
clear
i=1
while [ $i -le 100 ]
do
echo $i
i=`expr $i + 1`
done
o/p: prints 1 to 100

clear
i=1
while [ $i -le 100 ]
do
echo $i
if [ $i -eq 10 ]
then
break
fi
i=`expr $i + 1`
done

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

o/p: prints 1 to 10
continue:
continue is used to skip the rest of the statement in a loop . The loop does not
terminate but the program execution transfers directly to next iteration
of the loop.
Syntax:
while [ condition ]
do
statements
continue
skipped statements
done
Example:

clear
i=0 i
while [ $i -le 50 ] 0
do 1
i=`expr $i + 1` 2
if [ $i -lt 5 ] 3
then 4
continue 5
fi
echo $i # 5
done

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

o/p: prints 5 to 50

clear
i=0 i
while [ $i -le 50 ] 0
do 1
i=`expr $i + 1` 2
if [ $i -gt 5 ] 3
then 4
continue 5
fi 6
echo $i
done
o/p: prints

# Shell Program to reverse a given String

clear
echo “Enter any String:”
read str
len=`echo $str | wc -c`
echo “length of $str is :$len”
len=`expr $len – 1`
echo -e “The reverse of $str is:\c”
while [ $len -ge 1 ]
do

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

ch=`echo $str | cut -c $len`


echo -e “$ch\c” madam
len=`expr $len – 1`
done

# Shell program to find factorial of a number ( part a 1st program)


Ex: 4!=4X3X2X1=24
clear
echo “Enter any positive number:”
read n n i fact
i=1 4 1 1
fact=1 2 1
while [ $i -le $n ] 3 2
do 4 6
fact=`expr $fact \* $i` 5 24
i=`expr $i + 1`

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

done
echo “Factorial of $n is:$fact”
or
clear
echo “Enter any positive number:”
read n
num=$n num n fact
fact=1 4 4 1
while [ $n -ge 1] 3 4
do 2 12
fact=`expr $fact \* $n` 1 24
n=`expr $n – 1` 0 24
done
echo “factorial of $num is:$fact”

# Shell Program to find prime numbers between two limits


(PART A 2nd PROGRAM)
clear
echo “Enter m and n values:”
read m n
while [ $m -le $n ] m n flag i r
do 10 20 1 2 0

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

i=2;flag=1 11 0
while [ $i -lt m ] 12
do 13
r=`expr $m % i` 14
if [ $r -eq 0 ] 17
then
flag=0;
break;
else
i=`expr $i + 1`
fi
done
if [ $flag -eq 1 ]
then
echo -e “$m\t” 11 13 17 19
fi
m=`expr $m + 1`
done

# Shell program to find maximum and minimum of given set of


numbers
# PART A 3rd PROGRAM
clear
echo “How many entries:” n num i max min

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

read n 5 23 1 23 23
i=1 10 2 45 10
echo “Enter first number:” 45 3 08
read num 08 4
max=$num 30 5
min=$num
echo “Enter `expr $n – 1` numbers:”
while [ $i -lt $n ]
do
read num
if [ $num -gt $max ];then
max=$num
fi
if [$num -lt $min ];then
min=$num
fi
i=`expr $i + 1`
done
echo “maximum value is:$max”
echo “minimum value is $min”

# shell program to reverse a number and check it is palindrome or not.


PART A 4th PROGRAM

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

clear
echo “Enter any Number:” n num rev rem
read n 121 121 0 1
num=$n;rev=0 12 1 2
while [ $n -gt 0 ] 1 12 1
do 0 121
rem=`expr $n % 10`
rev=`expr $rev \* 10 + $rem 123 123 321
n=`expr $n / 10`
done
if [ $num -eq $rev ]
then
echo “$num is a palindrome”
else
echo “$num is not a palindrome”
fi
# Shell Program to count number of vowels in the given string
# PART A 5th PROGRAM
clear
echo “Enter any string:”
read str
len=`echo $str | wc -c`
len=`expr $len – 1`
i=1;vowels=0;other=0
while [ $i -le $len ]

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

do
ch=`echo $str | cut -c $ch`
case $ch in
[aeiouAEIOU]) vowels=`expr $vowels + 1`
;;
*) others=`expr $others + 1`
esac
i=`expr $i + 1`
done
echo “The number of vowels=$vowels”
echo “ The number of other characters is:$others

# Shell Program to check whether given string is palindrome or not


# part B 6th Program.
Example: Liril, madam, malayalam
clear
echo “Enter any String:”
read str
len=`echo $str | wc -c` str len ch1 ch2 i

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

len=`expr $len – 1` liril 5 l l 1


i=1 4 i i 2
while [ $i -le $len ] 3 r r 3
do 2 4
ch1=`echo $str | cut -c $i`
ch2=`echo $str | cut -c $len` ayaz 4 a z 1
if [ $ch1 != $ch2 ]
then
echo “$str is not a palindrome”
exit
fi
i=`expr $i + 1`
len=`expr $len – 1`
done
echo “$str is a palindrome

# Shell Program to print Nth Fibonacci Series


PART B 7th program
Example : 0 1 1 2 3 5 8 13 21
clear
echo “Enter Number of terms to display:”
read n n i f1 f2 f3

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

i=3;f1=0;f2=1 5 3 0 1 1
echo -e “The Fibonacci Series are:\c” 4 1 1 2
echo -e “$f1\t$f2\c” 5 1 2 3
while [ $i -le $n ] 6 2 3
do
f3=`expr $f1 + $f2`
echo -e “\c$f3\t”
f1=$f2
f2=$f3
i=`expr $i + 1`
done
o/p: The Fibonacci series are:0 1 1 2 3

# Shell Program to print the following Pattern 1


2 2
3 3 3
clear

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “Enter number of lines to display:”


read n
i=1
while [ $i -le $n ]
do
j=1
while [ $j -le $i ]
do
echo -e “\c $i”
j=`expr $j + 1`
done
i=`expr $i + 1`
echo
done

# Shell Program to print the following Pattern 1


1 2

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

1 2 3

clear
echo “Enter number of lines to display:”
read n
i=1
while [ $i -le $n ]
do
j=1
while [ $j -le $i ]
do
echo -e “\c $j”
j=`expr $j + 1`
done
i=`expr $i + 1`
echo
done

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

# Shell Program to print the following Pattern 1


0 1
1 0 1

clear
echo “Enter number of lines to display:”
read n
i=1
while [ $i -le $n ]
do
j=1
while [ $j -ge $i ]
do
echo -e “\c $j%2”
j=`expr $j + 1`
done
i=`expr $i + 1`
echo
done

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

#Shell program to display list of files in a given directory


clear
echo “Enter any directory name:”
read fname
if [ -d $fname ]
then
echo “List of files in $fname is:”
ls $fname
else
echo “ Please enter directory name”
fi

Shell program to illustrate the usage of break and continue statements


or
Menu Driven Program ( Part B 9 th program ]
clear
ans=’y’
while [ $ans = ‘y’ ]
do
echo -e “\n1.Listing of files\n2.Calender\n3.Date\n
4.Present Working Director y\n 5.Quit\n”
echo “Enter your choice:”
read ch
case $ch in

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

1) echo “\n List of Files in current working directory:”


ls ;;
2) echo “\n Calender\n”
cal ;;

3) echo -n“\nToday’s Date is:\n”


date ;;
4) echo -n “\n Present Working Directory”
pwd ;;
5) break;
*) echo “Invalid choice”
continue
esac

#Shell Program to copy one file to another file using command line
clear
echo “ File name to copy is:$1”
echo “New File name to copy:$2”
if [ $# -gt 2 -o $# -lt 2 ]
then
echo “Insufficient arguments”
exit
fi
cp $1 $2
echo “ Given File is:”
cat $1

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

echo “Copied File is:”


cat $2

# Shell Program to accept file name and check whether it is regular file or
directory file and display its permissions
clear
echo “Enter any file name:”
read name
if [ -f $name ]
then
echo “ $file is an ordinary file”
fi
if [ -d $name ]
then
echo “$file is a directory file”
fi
if [ -r $file ]
then
echo “$file is a readable”
fi
if [ -w $file ]
then
echo “$file is writable”

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

fi
if [ -x $file ]
then
echo “$file is executable
fi

PART A 10th program.


# Shell program to display all the file types and file permissions
clear
for name in *
do
if [ -f $name ]
then
echo “ $file is an ordinary file”
fi
if [ -d $name ]
then
echo “$file is a directory file”
fi
if [ -r $file ]
then
echo “$file is a readable”
fi

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

if [ -w $file ]
then
echo “$file is writable”
fi
if [ -x $file ]
then
echo “$file is executable
fi
done

(or)
clear
for i in *
do
if [ -f $i ]
then
file $i
ls -l $i
fi
done
Simple Examples:
Example 1:
Shell program to list all files and directories
clear
files=`ls`

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

for i in $files
do
echo $i
done
Example 2:
clear
set `date`
if [ $1 = “Tue” ]
then
echo “It is Tuesday”
elif [ $1 = “Sat” -o $1 = “Sun” ]
then
echo “It is weekend! Enjoy “
else
echo “ It is not weekend , Goto Work”
fi

Example : 03
clear
set `date`
case $1 in
Tue) echo “It is Tuesday”
;;
Sat | Sun) echo “It is Weekend!Enjoy”
;;

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

*) echo “ Goto Work, It is not Weekend


;;
esac

Redirection:
The Shell will associate with three files with the terminal , two for display and one
for keyboard.
These files are streams of characters which many commands see as input and
output.
The process of changing the input source or output destination is called
Redirection.
In UNIX, It is accomplished with following operators.
Input redirection (>)
Output redirection (>)
Output redirection with append (>>)
pipe (|)

There are 3 categories of redirection.


They are
1. Standard Input
` 2. Standard Output
3. Standard Error
1. Standard Input:
The file (stream) representing the input, connected to the keyboard

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

The Standard Input can come from


1. The default input source is keyboard
2. a file using redirection with < symbolic
3. another program using pipe (|)
Example:
1. $ wc <enter>
iam a good boy
<ctrl +d>
1 4 14
2. $wc < data.txt<enter>
20 50 120
3. sort data | head -2
Naveen
Siva
2. Standard Output:
The file (stream ) representing the output, connected to the display.
The Standard output can come from
1. The default output source is the monitor or terminal
2. The standard output can also be directed to a file using > and >>
operators.
3. another program using pipe
Example:
1. $ cat data.txt <enter>
content of data.txt
2. $ wc data.txt > newfile
$ cat $newfile

Downloaded by Palak Jaiswal ([email protected])


lOMoARcPSD|25874097

20 50 120
3. sort data | tail -2
kiran
siva
3.Standard Error:
The file(stream) representing the error messages also connected to the
display.

Example:
$ cat emp.lst <enter> if emp.lst is not created
cat:emp.lst:No Such file or directory

Downloaded by Palak Jaiswal ([email protected])

You might also like