Shell Programming Notes
Shell Programming Notes
What is UNIX ?
1. Unix is a computer operating system.
2. An operating system is the program that controls all the other part of a
computer system , both the H/W and S/W. It allocates the computer‘s
resources and schedules tasks. It allows you to make use of the facilities
provided by the system. Every computer requires an operating system.
3. UNIX is a multi-user , multi-tasking operating system. Multiple users may
have multiple tasks running simultaneously. This is very different than PC
operating systems.
4. UNIX is a machine independent operating system. Not specific to just one
type of the computer H/W. Designed form the beginning to be
independent of the computer hardware.
5. UNIX is a software development environment. Was born in and designed
to function within this type of environment.
6. The UNIX trademark previously owned by AT & T and then deeded to
UNIX Systems Laboratories (USL) , an AT & T subsidiary passed to
Novell when it acquired USL. After a brief period of negotiations with
rival UNIX vendors Sun Microsystems , Santa Cruz Operation ,
International Business Machines and Hewlett-Packard , Novell granted
exclusive licensing rights to the UNIX trademark to X/Open Co. Ltd , an
Open System industry standards branding agent based in the united
Kingdom.
History of UNIX
In 1965, Bell laboratories joined with MIT and General Electric to develop a new
operating system called Multics (Multiplexed Information Computing Service) , which
would provide multi-user , multi-processor and multi-level (hierarchical) file system.
In 1969, AT&T developed the first UNIX file system with a few utilities and gave the
name UNIX to it. In 1970, January 1 time zero for UNIX started. In 1973 , UNIX was re-
written in C by Dennis Ritchie . Being written in a high level language decreased the
effort to port it to new machines.
Features of UNIX
In 1983 , AT&T and Sun Microsystems jointly developed System V Release 4 (SVR 4).
This was later developed in UNIX ware and Solaris 2.
Boot Block: - This block contain a small boot program and partition table.
Super Block:-It contains globle information about the file system. It also
maintains a free list of inodes and data blacks that can be immediately allocated
by the kernel when creating a file.
This is mainly what it contains:-
The size of the file system.
The block size used by the file system.
The number of free data blocks available and a partial list of immediately
allocable free data blocks.
Number of free inodes available and a partial list of immediately usable
inodes.
Last time of updating.
The state of the file system (Whether ―clean ― or ―dirty‖).
Inode Block :-This region contains the inode for every file of the file system.
Data Block:-All data and programs created by users reside in this area.
Where
Option Description
-x Multicolumnar Output
-F Marks executables with *,directories with /, and symbolic links
with @
-a Shows all filenames beginning with a dot including . And ..
-R Recursive list (Directory., Subdirectory., files)
-r Sorts filename in reverse order
-1 One filename in each line
-l long listing (Seven attributes of a file)
-d dirname Lists only dirname if dirname is a directory
$ls
xyz, pqr, abc , MCA4
$ls –l
Total 72
-rw-r—r– 1 kumar metal 19514 May 10 13:54 MCA4
-rw-xr-r- 1 kumar metal 4174 May 10 15:01 xyz
drwxr-xr-x 2 kumar meatl 84 Feb 12 12:30 pqr
$ls –li
Total 72
vi (Visual) Editor
This editor can be invoked by typing vi at the $ prompt. If you specify a filename as an
argument to vi , then the vi will edit the specified files , if it exits.
vi [<filename>]
A status line at the bottom of the screen (25th line) shows the filenames, current
line and character position in the edited file.
vi + <line_number> <filename>
Edits the file specified in <filename> and places the cursor on the
<line_number>th line.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeeee
~
~
~
~
~
~
~
:wq
vi Modes
Shell
Insert Mode :-
1) The text should be entered in this mode and any key press in
this mode is treated as text.
i I
a A
o O
r R
s S
Command Mode:-
We can enter into this mode from insert mode by pressing the [Esc] key
and from Ex Mode by pressing [Enter Key].
Ex Command Mode:-
1. The Ex command mode (Saving files , find , replace etc ..) can be entered
at the last line of the screen in this mode.
2)We can enter into this mode from command mode by pressing [:] key.
Insert Commands
UNIT – II
Positional Parameter
O/P:-
You have the capacity to learn from mistakes. You
You0 You1
Q2. Ramesh‘s basic salary is input through the keyboard. His dearness allowance is
40% of basic salary and house rent allowance is 20% of basic salary. Write a program to
calculate his gross salary.
Solution :
Program
# Program : To calculate Salary of employee
#Output
#End of Program
Input
$sh gross_sal
Enter the basic salary of employee : 8000
Output
Q3. Write a shell program , which accepts the name of a file from the standard input and
performs the following test on it:
File Existence
File Readable
File Writeable
Both Readable and Writeable
Solution :
Description : To check the file is existence or readable or writeable or both
(Readable & Writeable).
Program
#Program Named : File Operation
if test –w $fname
then
echo ―File is writeable‖
else
echo ―File is not writeable‖
fi
Input
1. $ls –l test?.txt
2. $ chmod u+x filecheck
$ sh filecheck
Enter the filename :- test1.txt
3. $ sh filecheck
Enter the filename :- test2.txt
4. $ sh filecheck
Enter the filename :- test3.txt
Output
2. File is Exist
File is readable
File is writeable
File is both readable and writeable
3. File is Exist
File is readable
File is not writeable
File is not both readable and writeable
4. File is Exist
File is not readable
File is not writeable
File is not both readable and writeable
Q4. Write a Shell Script , which accepts the name of file from the standard input and then
performs the following operations
1) Enter the 5 names in file
2) Sort the names in existing file.
3) List unsorted and sorted file.
4) Quit
Solution :
Description : Lets enter the five file names and display in sorted and unsorted form.
Program
#Program : SORTED & UNSORTED FILE
sort $fname
echo ―SORTED LIST : ―
cat sortfile
#End of Program
Input
$sh sorting
IBRAHIM
DHENESH
PEETER
ABDULLAH
CHARLES
Output
UNSORTED LIST :
IBRAHIM
DHENESH
PEETER
ABDULLAH
CHARLES
SORTED LIST:
ABDULLAH
CHARLES
DHENESH
IBRAHIM
PEETER
UNIT - I
1. Log into a UNIX System and try to perform the following operations :
a) Create a directory mydir in the current directory.
b) Create another directory newdir within the directory mydir.
c) Copy the contents of mydir directory to the newdir directory.
d) Delete the directories mydir ans newdir at one shot.
2 .Write the command on followings :
a) List out all .txt Files.
b) List out all files content whose names start with ―M‖.
c) Show the contents of Files like Game1 ,Game2, Game3,Games4 & Game5 using
by File Name Substitution concepts.
3. Describe the various flavors of UNIX.
UNIT – II
1. Write shell script for the following , It should display menu for following
Display file contents with line number
Display the file contents with page break
Quit
2. Write a shell script for accepting the following information and storing in file.
i) customer name
ii) item description
iii) quantity
iv) rate
The user should get the facility to enter as many record as he wants.
UNIT - I
Ans 1:-
a. Create a directory mydir in the current directory.
mkdir mydir
cd mydir
mkdir newdir
cp mydir newdir
rmdir mydir/newdir
Ans 2 :-
ls *.txt
b. List out all files content whose names start with ―M‖.
ls M*
c. Show the contents of Files like Game1 ,Game2, Game3,Games4 & Game5
using by File Name Substitution concepts.
cat Game*
OR
cat Game[12345]
Xenix
FreeBSD , NetBSD & OpenBSD
Solaris
AIX
HP-UX
Digital UNIX
Tru64 UNIX
IRIX
SCO Open Server
SCO UnixWare
Linux
UNIT – II
Program
case $choice in
1) nl $fnm
;;
2) cat $fnm | more
;;
3) exit
;;
*) echo ― Sorry ! Try Again ........‖
esac
Input
$sh file_disp
||==============================================||
Menu Driven
||==============================================||
1.Displaying file contents with line number
2.Displaying the file contents with page break
3.Quit‖
||==============================================||
Output
1 I am student
2 My name is Harsh Wardhan
3 I am doing MCA from RCET, Bhilai
Ans 2:- Write a shell script for accepting the following information and storing in file.
v) customer name
vi) item description
vii) quantity
viii) rate
The user should get the facility to enter as many record as he wants.
Program
# Program : Customer Information
ch=‖y‖
while test $ch = ‖y‖
do
echo ―Enter the Name of Customer : ―
read cust_nm
echo ―Enter the Item Description : ―
read item_ds
echo ―Enter the Quantity of Item : ―
read qnty
echo ―Enter the Rate of Item : ―
read rate
echo $cust_nm:$item_ds:$qnty:$rate>Cust_info
cat Cust_info
Input
$sh cust_info
Output
Ans 3:-
and
Program
#program : Factorial
BEGIN {
END {
printf ―Actual Number is : %d ― , num1
printf ―The Factorial value : %d‖ , fact
} # End of END SECTION
Input
$sh factorial
Enter the Number : 5
Output
2. Define commands:
a) pwd
b) wc
c) ln
d) file
3. Write the various commands of vi-editor.
UNIT - II
2. Merge the contents of three files , sort them and display the sorted output on the screen
page by page.
3. Write a Menu Driven Shell Script to Copy, Edit, Rename and Delete a file.
Solution
UNIT – I
Ans 2: -
a) pwd :-[Present Working Directory / Print Working Directory]
This command displays the full pathname for the current working directory.
Example :-
$pwd
Output:- /home/bmi
Your present working directory is /home/bmi.
$rm test1.txt
$ls –l test2.txt
-rw-rw-r-- 1 bmi bmi 75 jan 13 14:35 test2.txt
d)file
This command lists the general classification of a specified file. It lets you to
know if the contents of the specified file is ASCII text , C program text , directory and
others.
Syntax:-
File <filename>
Example:-
$file test1.txt
Output
test1.txt : ASCII text.
$file *
Output
test1.test: ASCII text
xyz: Directory
Delete Commands
<n>X -Deletes specified number (n) of characters before the cursor position.
Replace Commands
Search Commands
Ex Mode Commands
SET Commands
The first is used to associate line numbers with the file . You are currently working with .
The second is used to ignore the case while searching a pattern in the file.
In addition to those two there are several other options that the user can set to customize
the environment of vi.
To get a list of all the options available with set , use the command:
(ESC): set all
Thought the list is long there are only a few which are most commonly used .
Type :To
Ctrl-gs how line number of current line.
Ctrl-l redraw the entire display.
:!sh fork a shell.
:type Ctrl-d to get back to vi.
. repeat last text change command at current cursor
position.
:set showmodes how when you are in insert mode.
:set ic ignore case when searching.
:set noic turn ignore case off.
:set nu turn on line numbering.
:set nonu turn line numbering off.
UNIT - II
Ans 2: Merge the contents of three files , sort them and display the sorted output on
the screen page by page.
Description : Merge the contents of only three files , sort them and display the
sorted output on the terminal.
Program
#Program : File Merge
$sh file_merge.sh
Enter the name of first File : Game1
Enter the name of second File : Game2
Enter the name of third File : Game3
Output
Contents of corresponding files….
-------------------------------------
Game1……
I like Hocky
Game2…..
I like Badminton
Game3…..
I like Cricket
-------------------------------------
Merging file Result……….
-------------------------------------
I like Hocky
I like Badminton
I like Cricket
-------------------------------------
Sorted Output………..
-------------------------------------
I like Badminton
I like Cricket
I like Hocky
-------------******----------------
Ans 3: Write a Menu Driven Shell Script to Copy, Edit, Rename and Delete a file.
Description : To perform the copy , edit , rename and delete operations
Program
#Program : FILE OPERATION
choice=‖y‖
while test $choice = ―y‖
do
echo ― MENU
1. COPY
2. EDIT
3. RENAME
4. DELETE ―
UNIT – I
1. What is inode?
2. Which of these commands will work ? Explain with reasons :
a) mkdir x y z
b) mkdir x x/y
c) mkdir x/y/z
d) mkdir –p x/y/z
e) rmdir x/y/z
f) rmdir –p x/y/z
UNIT – II
Solution
UNIT – I
1.What is Inode.
Ans: inode:- A structure maintained in a special area of the disk for storing the attribute of
a file. This table contains for every file its permission, ownership details, time stamps
and number of links .However ,it doesn’t contain the filename.
inode number :- A number identifying an inode for a file which is unique in a single file
system. It is displayed with the –i option of ls command.
B. mkdir x x/y
This command will create x as a subdirectory of current working
directory, y as subdirectory of x.
C. mkdir x/y/z
This command will create z as a subdirectory of y , y as subdirectory
of x , x as subdirectory of current working directory.
D. mkdir –p x/y/z
Then, for the current directory, a subdirectory named x is created .
Then for the directory x , a subdirectory named y is created. After that
the subdirectory z is created as a subdirectory of the directory y.
E. rmdir x/y/z
This command will remove the directory z only.
F. rmdir –p x/y/z
This command will remove the directories z , y and x consequently.
Commands
1. cat>FILE_PRO
File have Process and Processes have Life
^d
2. cat>>FILE_PRO
The file and process are the basic entities that support the UNIX system
^d
3. wc FILE_PRO
O/P : 2 20 113 FILE_PRO
4. cat foo foo foo
O/P : I like blue
I like blue
I like blue
5. mv bar1 bar2
(i) bar2 exists : It can be renamed with bar2
(ii)bar2 doesn‘t exist : It can be renamed with bar2
7. List all files which have filenames with only two characters.
ls ??
UNIT – II
Ans : A shell script is a script written for the shell, or command line interpreter, of an
operating system. It is often considered a simple domain-specific programming language.
Typical operations performed by shell scripts include file manipulation, program
execution, and printing text. Usually, shell script refers to scripts written for a Unix shell,
while COMMAND.COM (DOS) and cmd.exe (Windows) command line scripts are usually
called batch files, but here properties of both are discussed.
Many shell script interpreters double as command line interface, such as the various Unix
shells, Windows Power Shell or the MS-DOS COMMAND.COM. Others, such as AppleScript
or the graphical Windows Script Host (WScript.exe), add scripting capability to
computing environments without requiring a command line interface. Other examples of
programming languages primarily intended for shell scripting include DCL and JCL.
UNIT – I
UNIT – II
Solution
UNIT – I
Ans 1 :
Ans 2:
The Unix system is composed of several components that are normally packaged
together. By including — in addition to the kernel of an operating system — the
development environment, libraries, documents, and the portable, modifiable source-code
for all of these components, Unix was a self-contained software system. This was one of
the key reasons it emerged as an important teaching and learning tool and has had such a
broad influence.
The inclusion of these components did not make the system large — the original V7
UNIX distribution, consisting of copies of all of the compiled binaries plus all of the
source code and documentation occupied less than 10MB, and arrived on a single 9-track
magtape. The printed documentation, typeset from the on-line sources, was contained in
two volumes.
The names and filesystem locations of the Unix components has changed substantially
across the history of the system. Nonetheless, the V7 implementation is considered by
many to have the canonical early structure:
The 'man' command can display a 'man page' for every command on the system,
including itself.
Documentation — Unix was the first operating system to include all of its
documentation online in machine-readable form. The documentation included:
o man — manual pages for each command, library component, system call,
header file, etc.
o doc — longer documents detailing major subsystems, such as the C
language and troff
Ans 3 :
1. sed [Stream Editor]:-
This is a multipurpose tool which combines the work of several filters. It is
derived from ed , the original editor. sed performs non-interactive
operations on a data stream – hence its name .
This command displays the 1st two lines of the emp.txt file.
O/P:- NO RESULTS
fgrep :- It is similar to grep command. But It does not accept regular expressions unlike
grep.
$ $fgrep ―computer‖ emp.txt :-
1001 Ram Computer CS
$fgrep ―com*‖ emp.txt
NO SUCH RESULT
Ans 4 :
1.cmp [Compare]
This command is used compare two files.
Syntax:-
cmp <filename1> <filename2>
This command reports the first instance of differences between the specified files.
That is the two files are compared byte by byte and the location of the first mismatch is
echoed to the screen.
Example:-
$cat file1.txt
I am Ram
What is your name?
$cat file2.txt
I am Ram
What are you doing?
2. comm [Common]
This command uses two sorted files as argumnets and reports what is common.It
compares each line of the first with its corresponding line in the second file. The output
of this command is in three column as follows:
Column1 : Contains lines common for both filename 1 and filename2
Column2 : Contains lines unique to filename2.
Column3 : Contains lines unique to filename1.
Syntax:-
comm [-option] <filename1> <filename2>
Option:-
1 - Suppresses listing of column1
2 - Suppresses listing of column2
3 - Suppresses listing
Example:-
$cat file1.txt $cat file2.txt
I am Ram I am Ram
What is your name? What are you doing?
awk is a powful Unix command. It allows the user to manipulate files that are
structured as columns of data and strings.
Outline
o General structure of awk scripts
o Elementary awk programming
Elementary examples
o Advanced awk programming
Advanced examples
o Important things which will bite you
Ans 2:-
% echo $history
SHELL variables are both set and displayed using the set
command. They can be unset by using the unset command.
% set | less
Environment Variable : -
% echo $OSTYPE
Ans 3:-
Write a shell program to find out the number of positive and negative numbers present in
a list of numbers supplied as command line arguments.
Description : Script that counts the number of positive and negative numbers.
Program
echo ―Script that counts the number of positive and negative numbers‖
p=0
n=0
for i in $*
do
if test $i –gt 0
then
p=`expr $p + 1`
else
n=`expr $n +1`
fi
done
1 3 -4 -5 6 -7 8 -7 9 -9
Ans 4 : -
Write a shell script to accept a number and print it in reverse.
Program
#Program : Reverse Number
$sh reverse
Enter the Number : 123
Output
UNIT – I
1. Define UNIX?
3. Short notes on followings :
1. cmp
2. comm.
3. wc
UNIT – II
$cat file2.txt
I am Ram
What are you doing?
2. comm [Common]
This command uses two sorted files as argumnets and reports what is common.It
compares each line of the first with its corresponding line in the second file. The output
of this command is in three column as follows:
Column1 : Contains lines common for both filename 1 and filename2
Column2 : Contains lines unique to filename2.
Column3 : Contains lines unique to filename1.
Syntax:-
comm [-option] <filename1> <filename2>
Option:-
1 - Suppresses listing of column1
2 - Suppresses listing of column2
3 - Suppresses listing
Example:-
$cat file1.txt $cat file2.txt
I am Ram I am Ram
What is your name? What are you doing?
3. wc [Word Count]
This command is used to display the number of lines,words and characters of
information stored on the specified file.
Syntax:-
wc [-option] <File_Name>
Where
l - Displays the number of lines in the file
w – Displays the number of words in the file
c – Display the number of characters in the file
Question Bank
UNIT -I
2. What is UNIX File System? Hence explain the Boot Block, Super Block, Inode
Block and Data Block with suitable diagram. What should be the size of block in
UNIX File System.
3. What is UNIX Operating System? Explain its various features.
4. Write the advantages and disadvantages of UNIX Operating System.
5. What is Inode Numer? Write the various information stored in inode table and
information that are not stored in Inode Table. Write difference between ln ,mv
,cp command wirh respect to Inode No.
6. Explain use of chmode command with example in symbolic mode and in absolute
mode.
7. Draw the structure of UNIX Operating System. And explain the responsibilities of
Kernel and Shell.
8. What is Filter? Write any five commands that are filters & that are not filters.
9. Explain the three different modes of VI-editor with example.
10. Gives the name of three modes of vi-editor. And write commands for following in
VI-editor.
1. Save files and quiets editing mode.
2. Delete current line & five line below
3. Goes to the line number 40
UNIT –II
1. What is Shell Programming ? Describe the various functions of Shell
programming.
2. What is Shell ? Explain the types of Shell.
3. What is shell script? What are different ways of executing shell scripts? Writ the
shell script to delete all files with .old extension copy all file with . c extension
and remove all file , to some other directory with . exe extension.
4. Explain the differences between the Bourne Shell and C Shell. Also write a shell script
the compare the contents of two file and delete one of them. If both the file are similar
then display proper message.
5. Write the use of shift command with example.
6. Explain shell meta character and environment variable with suitable example.
7. Explain the positional parameters and the use of set commands with suitable diagram.
8. What is positional parameters? What are different notations used for position parameter.
Explain the difference between $* and $@.
9. Write awk command for the following:-
a. Print all lines in which the first field is ‗Prata‘ and fourth is not Batch‘.
b. Print all lines where sum of first and second field is not greater than third
field.
c. Print sum of each field of a file.
d. Print fifth field of these lines that contain the pattern ‗UNIX‘
e. Print the number of occurrence of word ‗UNIX‘, ‗UNUX‘ & ‗ZENIX‘
f. Print sum of each field of a numeric file.
10. Explain any six system shell variable and their meaning