Sie sind auf Seite 1von 44

UNIT – 1

Q1.What is UNIX ? Explain its History and features


Ans:-

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.

In 1980, BSD 4.1 (Berkelely Software Development ) was developed.

In 1983, SunOs, BSD 4.2 , System were released.


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.

Features of UNIX

1. The file and Process


2. Multi-user
3. Multi-tasking
4. The Building Block Approach
5. UNIX Tool-Kit
6. Pattern Matching
7. Programming Facility
8. Documentation
9. Communication System
10. Security
11. File Encryption/Decryption
12. Portability

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.

Q2. Explain the UNIX File System.


Ans : UNIX File System :-

Components of UNIX File System

 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.

3. Explain the ls command with all options.


1.ls(list)-To shows the list of files and direrctories.
Syntax: ls [-option] [name of file name/ directory name]

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

Q4.What is vi-editor? Explain its modes.


Ans :

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

Insert/Input Mode Command Mode Ex-Mode


T
H Input Mode Ex-Mode
E [Esc]
T
H
:
[Enter]
R i,I,a,A,o,O,r,
E R,s, and S
E Command
M Mode
O
D
E
vi foo :x, :q
S :wq & ZZ

Shell

Insert Mode :-

1) The text should be entered in this mode and any key press in
this mode is treated as text.

2) We can enter into this mode from command mode by pressing


any of the keys:

i I
a A
o O
r R
s S
Command Mode:-

It is the default mode when we start up vi-editor.


All the commands on vi-editor (Cursor movement text manipulation etc. )
should be used in this 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

i Inserts before cursor.


I Inserts at the beginning of the current line.
a Appends at the end of the current line.
A Appends at the start of the current line.
o Inserts a blank line below the current line.
O Inserts a blank line above the current line.

UNIT – II

Q1. Explain the set command with positional parameter.


Ans: Set command

$set friends come and go but enemies accumulate


$echo $1 $2 $3 $4 $5 $6 $7
O/P:- friends come and go but enemies accumulate
$echo $1 $2 $3 $4
O/P:- friends come and go

Positional Parameter

$0 – Refers to the name of the command.


$1 – Refers to the first argument.
$2 – Refers to the second argument. … & so on
$* - Refers all the argument.
$# - Refers the total no. of arguments.
$? - Returns the exit status of last executed command.
$! - Returns the Process Identification number (PID) of last background command
(command ended with & )
$$ - Returns the PID of the current shell.
Example :

$set Do you want credit or results


$set A smiling face is always beautiful
$echo $1 $2 $3 $4 $5 $6
O/P:- A smiling face is always beautiful
$cat lucky
O/P:- Give luck a little time
$set `cat lucky`
$set $1 $2 $3 $4 $5
O/P:-Give luck a little time

$set Do you want credit or results


$set A smiling face is always beautiful
$echo $1 $2 $3 $4 $5 $6
O/P:- A smiling face is always beautiful
$cat lucky
O/P:- Give luck a little time
$set `cat lucky`
$set $1 $2 $3 $4 $5
O/P:-Give luck a little time

Using Shift on Positional Parameters

―Set is used to set upto 9 words‖


$set You have the capacity to learn from mistakes.
You will learn a lot in your life.

$echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11

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 :

Description : To calculate the Gross Salary of any Employee including DA,HRA


and BASIC SALARY).

Program
# Program : To calculate Salary of employee

echo ―Enter the basis salary of employee : ―


read bs

da=`expr $bs \* 40 / 100`


hra=`expr $bs \* 20 / 100`
gs=`expr $bs + $da + $hra`

#Output

echo ―Basic Salary : $bs―


echo ― DA : $da‖
echo ― HRA : $hra‖
echo ― Gross Salary: $gs‖

#End of Program
Input

$sh gross_sal
Enter the basic salary of employee : 8000

Output

Basic Salary : 8000


DA : 3200
HRA : 1600
Gross Salary : 12800

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

echo ―Enter the filename : ―


read fname
if test –e $fname
then
echo ―File is Exist‖
else
echo ―File is not Exist‖
fi
if test –r $fname
then
echo ―File is readable‖
else
echo ―File is not readable‖
fi

if test –w $fname
then
echo ―File is writeable‖
else
echo ―File is not writeable‖
fi

if test –r $fname -a -w $fname


then
echo ―File is both readable and writeable‖
else
echo ‖File is not both readable and 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

1. -rw-rw-r-- 1 bmi bmi 64 Jan 4 10:17 test1.txt


-r—rw-r-- 1 bmi bmi 64 Jan 4 10:17 test2.txt
------------ 1 bmi bmi 64 Jan 4 10:17 test3.txt

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

echo ‖Enter the file_name : ‖


read fname

echo ―Enter five names and press ^d at the end.‖


cat > $fname

echo ―Unsorted LIST: ―


cat fname

sort $fname
echo ―SORTED LIST : ―
cat sortfile

#End of Program

Input
$sh sorting

Enter the file name: fsu_nm


Enter five names and press ^d at the end.

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.

3. Calculate factorial value of any number using awk command


Solution

UNIT - I
Ans 1:-
a. Create a directory mydir in the current directory.

mkdir mydir

b. Create another directory newdir within the directory mydir.

cd mydir
mkdir newdir

c. Copy the contents of mydir directory to the newdir directory.

cp mydir newdir

d. Delete the directories mydir ans newdir at one shot.

rmdir mydir/newdir

Ans 2 :-

a. List out all .txt Files.

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]

Ans 3:- UNIX FLAVORS:

 Xenix
 FreeBSD , NetBSD & OpenBSD
 Solaris
 AIX
 HP-UX
 Digital UNIX
 Tru64 UNIX
 IRIX
 SCO Open Server
 SCO UnixWare
 Linux

UNIT – II

Ans 1 :- Description : In this program , we make a menu for displaying file


contents with line number , Display the contents with page break and quit.

Program

#Program : Displaying file contents


echo ― ||==============================================||‖
echo ― Menu Driven ―
echo ― ||==============================================||‖
echo ― 1. Displaying file contents with line number‖
echo ― 2.Displaying the file contents with page break‖
echo ― 3.Quit‖
echo ― ||==============================================||‖

echo ―Enter the name of existing File Name : ―


read fnm
echo ―Enter your choice : ―
read choice

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‖
||==============================================||

Enter the name of existing File Name : file1


Enter your choice : 1

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.

Description : To maintain the record of Customer.

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

echo ―Do you want to continue : ―


read ch
done
#Output

cat Cust_info

#End of the Program

Input

$sh cust_info

Enter the Name of Customer : Ram


Enter the Item Description : Television
Enter the Quantity of item : 10
Enter the Rate of Item : 100000

Do you want to continue :y

Enter the Name of Customer : Lay


Enter the Item Description : Mobile
Enter the Quantity of item :5
Enter the Rate of Item : 100000

Do you want to continue :n

Output

Ram Television 10 100000


Lay Mobile 5 100000

Ans 3:-

Description : In mathematics, the factorial of a non-negative integer n, denoted by


n!, is the product of all positive integers less than or equal to n. For example,

and

where n! represents n factorial. The notation n! was introduced by Christian Kramp in


1808.

Program
#program : Factorial

BEGIN {

print ― Calculation of Factorial Value ―


print ―Enter the Number : ―
getline num
num1 = num
fact = 1
while ( num > 0)
{
fact = fact * num
num = num – 1
}
} # End of BEGIN SECTION

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

Calculation of Factorial Value


Actual Number is :5
The Factorial value : 120
UNIT – I

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.

b)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

Examples:- Command Output

$cat file1 I am file1


$wc file1 1 3 10 file1
$wc –l file1 1 file1
$wc –w file1 3 file1
$wc –c file1 10 file1
c) ln(Link)
This command is used to establish on additional filename to a specified file.It
doesn‘t mean that creating more copies of the specified file.
Syntax:-
ln <filename> <additional_filename>
Where <Filename> is the file name for which <additional_filename> is to located
on any directory. Thus UNIX allows a file to have more than one name and yet maintain
a single copy in the disk. But changes to one of these files are also reflected in the disk
.But changes to one of these files are also reflected to the others. If you delete one
filename using rm command , then the other link names will still exist.
Example:-
$ls –l test1.txt
-rw-rw-r-- 1 bmi bmi 75 jan 13 14:35 test1.txt

$ln test1.txt test2.txt


$ls –l test*.txt
-rw-rw-r-- 2 bmi bmi 75 jan 13 14:35 test1.txt
-rw-rw-r-- 2 bmi bmi 75 jan 13 14:35 test2.txt

$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

Ans 3: - Various commands of vi-editor:-


Insert Commands

i Inserts before cursor.


I Inserts at the beginning of the current line.
a Appends at the end of the current line.
A Appends at the start of the current line.
o Inserts a blank line below the current line.
O Inserts a blank line above the current line.

Delete Commands

x -Deletes a character at the cursor position.

<n>x-Deletes specified number (n) of character.

X -Deletes a character before the cursor position.

<n>X -Deletes specified number (n) of characters before the cursor position.

dw -Deletes from current position to end of the current word.


db -Deletes from cursor position to beginning of current word.
dd -Deletes current line.
<n>dd -Deletes specified number of lines (n) from the current line.

Replace Commands

r – Replaces single character at the cursor position.


R –Replaces characters until[ESC] key is pressed from current cursor
position.
s – Replaces single character at the cursor position with any number of
character.
S – Replaces entire line.

Search Commands

/string [Enter] – Searches the specified string forward in the


file.
?string [Enter]- Searches the specified string backward in the
file.
n - Finds the next string in the same direction.
N - Finds the next string in the opposite direction.
Yanking (Copy & Paste) Commands

yy or (y) : Yanks the current line into the buffer (Copy).


nyy or ny : Copies the ‗n‘ lines from the current line to the
buffer.
p : Paste the yanked text below the current line.
P : Paste the yanked text above the current line.

Ex Mode Commands

:w – Saves file without quitting


:w <filename> - Saves the content into a file specified in
<filename>
:x or :wq – Saves file and quits from vi.
:q! – Quits from vi without saving.

SET Commands

The two set command i.e. set nu and set ic.

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 .

A list of these along with the affect of each is shown in figure:-

:set nu Set display of line numbers on.


:set nonu Set display of line numbers off (Default).
:set eb Beep the speaker when an error occurs (Default).
:set noeb Do not Beep the speaker when an error occurs.
:set ai Set auto indent on.
:set noai Set auto indent off (default).
:set ic Ignores case while searching a pattern.
:set noic Do not Ignores case while searching a pattern (default).

.exrc Profile and Miscellaneous Commands

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

echo ― Enter the name of first File : ―


read file1
echo ― Enter the name of second File : ―
read file1
echo ― Enter the name of third File : ―
read file1

echo ― Contents of corresponding files….‖


echo ―--------------------------------------―
echo ― Game 1 …..‖
cat Game1
echo ― Game 2 …..:
cat Game2
echo ― Game 3 …..‖
cat Game3
echo ―--------------------------------------―

#Merging the Three files ……..

cat $file1 $file2 $file3 > Newfile


echo ―Merging files Result ……‖
echo ―--------------------------------―
cat Newfile
echo‖---------------------------------―
echo ―Sorted Output…………….‖
echo‖---------------------------------―
sort Newfile | more
echo ―-------------******-------------―
#End of Program
Input

$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 ―

Echo ―ENTER YOUR OPTION : ―


read option
echo ―Enter source filename : ―
read source
case $option in
1) echo ―Enter destination filename : ―
read target
cp $source $target
;;
2) vi $course
;;
3) echo ―Enter the new name of the file : ―
read target
mv $source $target
;;
3) rm $source
;;
esac
echo ―Do You Want To Continue [y|n] : ―
read choice
done
Input $sh file_opr.sh
MENU
1. COPY
2. EDIT
3. RENAME
4. DELETE
ENTER YOUR OPTION : 1
Enter source filename : filemange.sh
Enter destination filename : fm.sh
Do You Want To Continue [y|n] : y
MENU
1. COPY
2. EDIT
3. RENAME
4. DELETE
ENTER YOUR OPTION : 2
Enter source filename : fm.sh
- The file –fm is displayed on the vi editor . Quit vi after editing.
Do You Want To Continue [y|n] : y
MENU
1. COPY
2. EDIT
3. RENAME
4. DELETE
ENTER YOUR OPTION : 3
Enter source filename : fm.sh
Enter the new name of the file : fmanage.sh
Do You Want To Continue [y|n] : y
MENU
1. COPY
2. EDIT
3. RENAME
4. DELETE
ENTER YOUR OPTION : 4
Enter source filename : fmanage.sh
Do You Want To Continue [y|n] : n
Output
cat filemange.sh # file not found
cat fm.sh # UNIX is an Operating System.

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

3.Perform the following


1.Create a file ―FILE_PRO‖ and the contents of file are ―File have Process and
Processes have Life‖.
2.Append the file ―FILE_PRO‖ and add new contents such as ―The file and
process are the two basic entities that support the UNIX system.
3.Count the File ―FILE_PRO‖ , how many Lines,Words & Characters are there?
4.What will cat foo foo foo display?
5.How does the command mv bar1 bar2 behave , where both bar1 and bar2 are
directories when (i) bar2 exists and (ii) bar2 doesn‘t exist?
6. The command cmp foo1 foo2 displays nothing. What does it
indicates?
7. List all files which have filenames with only two characters.
4. 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.

UNIT – II

1. What is shell script?


2. Explain the set command with positional parameter.
3. 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.
4. 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
UNIT – II

1. What is shell script?


2. Explain the set command with positional parameter.
3. 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.
4. 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
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.

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
Ans:-
A. mkdir x y z
This command will create ‗x‘ , ‗y‘ & ‗z‘ respectively , a subdirectory
of the current directory.

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.

3.Perform the following


1. Create a file ―FILE_PRO‖ and the contents of file are ―File have Process and
Processes have Life‖.
2. Append the file ―FILE_PRO‖ and add new contents such as ―The file and process
are the two basic entities that support the UNIX system.
3. Count the File ―FILE_PRO‖ , how many Lines,Words & Characters are there?
4. What will cat foo foo foo display?
5. How does the command mv bar1 bar2 behave , where both bar1 and bar2 are
directories when (i) bar2 exists and (ii) bar2 doesn‘t exist?
6. The command cmp foo1 foo2 displays nothing. What does it
i. indicates?
7. List all files which have filenames with only two characters.
Ans:-

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

6. cmp foo1 foo2 # ―displays nothing ―

!!! ― It indicate the prompt‖

7. List all files which have filenames with only two characters.

ls ??

UNIT – II

1. What is Shell script.

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

1.Define portability, modifiability , Open Source & Open System?


2. Exaplain the components of UNIX Operating System.
3.Explain the following command with example:
sed
grep
4. Short notes on followings :
1. cmp
2. comm.
3. wc

UNIT – II

1. Define awk command.


2. Explain the Shell Variable & Environment Variable.
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.
4. Write a shell script to accept a number and print it in reverse.

Solution

UNIT – I
Ans 1 :

Portability. It was the first widely-used operating system written in a high


level programming language, C, making it easier to port to different hardware
architectures.

Modifiability. Since it was written in C, modifications and enhancements are


relatively easier to make.

Open source. It was developed at AT&T Bell Labs, a non-profit research


institution, so the source code was permitted to be published and shared with
others.

Open system. Research scientists designed it as an open, modular system,


with a host of utilities and features to assist with the development and
integration of new applications.

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:

Kernel — source code in /usr/sys, composed of several sub-components:


o conf — configuration and machine-dependent parts, including boot code
o dev — device drivers for control of hardware (and some pseudo-hardware)
o sys — operating system "kernel", handling memory management, process
scheduling, system calls, etc.
o h — header files, defining key structures within the system and important
system-specific invariables
Development Environment — Early versions of Unix contained a development
environment sufficient to recreate the entire system from source code:
o cc — C language compiler (first appeared in V3 Unix)
o as — machine-language assembler for the machine
o ld — linker, for combining object files
o lib — object-code libraries (installed in /lib or /usr/lib) libc, the system
library with C run-time support, was the primary library, but there have
always been additional libraries for such things as mathematical functions
(libm) or database access. V7 Unix introduced the first version of the
modern "Standard I/O" library stdio as part of the system library. Later
implementations increased the number of libraries significantly.
o make - build manager (introduced in PWB/UNIX), for effectively
automating the build process
o include — header files for software development, defining standard
interfaces and system invariants
o Other languages — V7 Unix contained a Fortran-77 compiler, a
programmable arbitrary-precision calculator (bc, dc), and the awk
"scripting" language, and later versions and implementations contain
many other language compilers and toolsets. Early BSD releases included
Pascal tools, and many modern Unix systems also include the GNU
Compiler Collection as well as or instead of a proprietary compiler
system.
o Other tools — including an object-code archive manager (ar), symbol-
table lister (nm), compiler-development tools (e.g. lex & yacc), and
debugging tools.
Commands — Unix makes little distinction between commands (user-level
programs) for system operation and maintenance (e.g. cron), commands of
general utility (e.g. grep), and more general-purpose applications such as the text
formatting and typesetting package. Nonetheless, some major categories are:
o sh — The "shell" programmable command-line interpreter, the primary
user interface on Unix before window systems appeared, and even
afterward (within a "command window").
o Utilities — the core tool kit of the Unix command set, including cp, ls,
grep, find and many others. Subcategories include:
 System utilities — administrative tools such as mkfs, fsck, and
many others
 User utilities — environment management tools such as passwd,
kill, and others.
o Document formatting — Unix systems were used from the outset for
document preparation and typesetting systems, and included many related
programs such as nroff, troff, tbl, eqn, refer, and pic. Some modern Unix
systems also include packages such as TeX and Ghost script.
o Graphics — The plot subsystem provided facilities for producing simple
vector plots in a device-independent format, with device-specific
interpreters to display such files. Modern Unix systems also generally
include X11 as a standard windowing system and GUI, and many support
OpenGL.
o Communications — Early Unix systems contained no inter-system
communication, but did include the inter-user communication programs
mail and write. V7 introduced the early inter-system communication
system UUCP, and systems beginning with BSD release 4.1c included
TCP/IP utilities.

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 .

sed uses instructions to act on text. An instruction combines an address


for selecting lines , with an action to be taken on them as shown by the
syntax:-

sed [options]/[Edit Commands] ‗address action‘ files


The address and action are enclosed within single quotes. Addressing in sed is
done in two ways:-

 By one or two line numbers.


 By specifying a /- enclosed pattern which occurs in a line.

Where edit commands can be:-

i – Inserts after line


a – Appends after line
c – Changes lines
d – Deletes lines
p – Prints lines
q – Quits
Example1:-$sed ‗2q‘ emp.txt
Output:-
1001 John Computer CS
1002 Merry Electronics ET

This command displays the 1st two lines of the emp.txt file.

Example2:- $sed ‗2d‘ emp.txt


Output:-
1001 John Computer CS
1003 Ram Computer CS
This command displays the contents of emp.txt by deleting the second line.

Example3:- $sed –n ‗2p‘ emp.txt


Output:-
1002 Merry Electronics ET
This command displays the second line of the emp.txt.

Example4:- $sed –n ‗2,4p‘ emp.txt


This command displays the lines 2 through 4 of emp.txt.

Example5:- $sed –n ‗$p‘ e mp.txt


This command displays the last line of emp.txt.

2. grep [Global Regular Expression Printing] :-


This command is used to search for a specified pattern form a specified file and
display those lines containing the patter.
Syntax:-
grep [-option] pattern <filename>
Where options
-b ignores spaces , tab.
-i Ignore case
-v Displays only the lines that do not match the specified pattern.
-e Displays the total number of occurrences of the pattern in the file.
-n Displays the resultant lines along with their line number.
Example:-
$cat emp.ext
1001 Ram Computer CS
1002 Merry Electronics ET
1003 John Computer CS
$grep ―CS‖ emp.txt
o/p:- 1001 Ram Computer CS
1003 John Computer CS

Regular Expression Character Set


*: Represents any number of characters
?: Represents any single character.
[r1-r2]: Range
[^abcd] : Matches a single character which is not a,b,c or d.
^[character]: Matches the lines that are beginning with the character specified in
<Character>
[character]$ :Matches the lines that are ending with the character specified in <character>
Example:-
$grep ―Com*‖ emp.txt
o/p:- 1001 Ram Computer CS
1003 John Computer CS
Related commands with grep:- 1.egrep [ Extended grep]
2.fgrep [ Fixed grep]
egrep :- This command offers additional features than grep. Multiple patterns can be
searched by using pipe symbol.

$grep ―Ram | hari‖ emp.txt

O/P:- NO RESULTS

$ $egrep ―Ram | hari‖ emp.txt :-


1001 Ram Computer CS
1003 John Computer CS

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?

$cmp file1.txt file2.txt


Output
file1.txt file2.txt differ : byte 10 char 1, line2

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?

$comm file1.txt file2.txt


Output:-
I am Ram
What are you doing?
What is your name?
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

Examples:- Command Output

$cat file1 I am file1


$wc file1 1 3 10 file1
$wc –l file1 1 file1
$wc –w file1 3 file1
$wc –c file1 10 file1
UNIT – II
Ans 1: - awk command :

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

General structure of awk (Aho, Weinberg, and Kernighan)


o awk, oawk, nawk, gawk, mawk
 The original version, based on the first edition of The awk
Programming Language was called awk
 2nd edition of book led to nawk
 Unices usually ship with three different names for awk: oawk,
nawk, and awk; either oawk=awk or nawk=awk.
 gawk is the FSF version.
 mawk is a speedier rewrite which does a partial compilation
o The awk command line is:

awk [program|-f programfile] [flags/variables] [files]

Command line flags


o -f file -- Read the awk script from the specified file rather than the
command line
o -F re -- Use the given regular expression re as the field separator rather
than the default "white space"
o variable=value -- Initialize the awk variable with the specified

An awk program consists of one or more awk commands separated by either \n or


semicolons.

Ans 2:-

Shell Variable :- Variables are a way of passing information from the


shell to programs when you run them. Programs look "in the
environment" for particular variables and if they are found will use the
values stored. Some are set by the system, others by you, yet others
by the shell, or any program that loads another program.

Standard UNIX variables are split into two categories, environment


variables and shell variables. In broad terms, shell variables apply
only to the current instance of the shell and are used to set short-
term working conditions; environment variables have a farther
reaching significance, and those set at login are valid for the duration
of the session. By convention, environment variables have UPPER
CASE and shell variables have lower case names

An example of a shell variable is the history variable. The value of


this is how many shell commands to save, allow the user to scroll
back through all the commands they have previously entered.
Type

% echo $history

More examples of shell variables are

cwd (your current working directory)


home (the path name of your home directory)
path (the directories the shell should search to find a command)
prompt (the text string used to prompt for interactive commands
shell your login shell)
Finding out the current values of these variables.

SHELL variables are both set and displayed using the set
command. They can be unset by using the unset command.

To show all values of these variables, type

% set | less

Environment Variable : -

An example of an environment variable is the OSTYPE variable.


The value of this is the current operating system you are using.
Type

% echo $OSTYPE

More examples of environment variables are

USER (your login name)


HOME (the path name of your home directory)
HOST (the name of the computer you are using)
ARCH (the architecture of the computers processor)
DISPLAY (the name of the computer screen to display X
windows)
PRINTER (the default printer to send print jobs)
PATH (the directories the shell should search to find a command)

Finding out the current values of these variables.

ENVIRONMENT variables are set using the setenv command,


displayed using the printenv or env commands, and unset using
the unsetenv command.

To show all values of these variables, type


% printenv | less

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

#Program : Positive & Negative Number

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

echo ― The number of positive number are : $p‖


echo ― The number of negative number are : $n‖
Input
$sh Pos_Neg_Num 1 3 -4 -5 6 -7 8 -7 9 -9

Script that counts the number of positive and negative numbers

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.

Description : To accept a number & print it in reverse.

Program
#Program : Reverse Number

echo ―Enter the Number : ―


read num
num1=$num
rev=0

while test $num –gt 0


do
digit=`expr $num % 10`
rev=`expr $rev \* 10 + $digit`
num=`expr $num / 10`
done

echo ―Actual Number is : $num1‖


echo ―Reverse Number is : $rev‖
Input

$sh reverse
Enter the Number : 123

Output

Actual Number is : 123


Reverse Number is : 321

UNIT – I

1. Define UNIX?
3. Short notes on followings :
1. cmp
2. comm.
3. wc
UNIT – II

1. What is shell script?


2. Explain the Shell Variable & Environment Variable.
SOLUTION
Ans 1. UNIX :-
o Unix is a computer operating system.
o 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.
o 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.
o 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.
o UNIX is a software development environment. Was born in and designed
to function within this type of environment.
o 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.
Ans 3:-
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?

$cmp file1.txt file2.txt


Output
file1.txt file2.txt differ : byte 10 char 1, line2

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?

$comm file1.txt file2.txt


Output:-
I am Ram
What are you doing?
What is your name?

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

Examples:- Command Output

$cat file1 I am file1


$wc file1 1 3 10 file1
$wc –l file1 1 file1
$wc –w file1 3 file1
$wc –c file1 10 file1
.

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

11. Write the commands for following:-


1. To search a Pattern ‗Swine ‗ or ‗swine‘ in a file.
2. To search all lines that contains a pattern ‗UNIX SYSTEM‘ or ‗LINUX
SYSTEM‘.
3. Substitute all occurrences of ‗UNIX‘ to ‗LINUX‘.
12. Write the answer on following questions:
1. How does the commands mv bar1 bar2 behave where both bar1 and bar2
are directories when (i) bar2 exist and (ii) bar2 doesn‘t exits?
2. Explain the significance of the following commands (i) ls –ld (ii) ls –l
3. The command and cmp foo1 foo2 displays nothing. What does it indicate?
13. Which of these commands will work? Explain with reasons.
1. mkdir a b c
2. mkdir a/b/c
3. mkdir a b/c
4. mkdir –p a/b/c
5. rmdir a b c
6. rmdir a/b/c
7. rmdir –p a/b/c

14. Explain the following command with example:


1. sed
2. grep
14. Which of these commands will work? Explain with reasons.
1. ls
2. ls –l
3. ls –l game
4. ls –l game?
5. ls –l game*
6. ls –l game[12345]
7. ls –l game[!12345]
8. ls –l game[1-5]
9. ls –l game[1-5,a-z,A-Z]
10. ls –l>xyz
15. Which of these commands will work? Explain with reasons.
i. cat >game
ii. cat game>game1
iii. cat game
iv. cat game?
v. cat game*
vi. cat game[12345]
vii. cat game[!12345]
viii. cat game[1-5]
ix. cat game[1-5,a-z,A-Z]
x. cat game | sort

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

Das könnte Ihnen auch gefallen