ge2155 full lab manual
TRANSCRIPT
-
7/28/2019 GE2155 full lab manual
1/81
GE2155 COMPUTER PRACTICE LABORATORY II L T P C
0 1 2 2
SYLLABUS
1. UNIX COMMANDS 15
Study of Unix OS - Basic Shell Commands - Unix Editor
2. SHELL PROGRAMMING 15
Simple Shell program - Conditional Statements - Testing and Loops
3. C PROGRAMMING ON UNIX 15
Dynamic Storage Allocation-Pointers-Functions-File Handling
TOTAL : 45 PERIODS
-
7/28/2019 GE2155 full lab manual
2/81
TABLE OF CONTENTS
Ex. No Lab # Name of the experiment Page No
1 BASIC UNIX COMMANDS
1.1 1 STUDY OF UNIX OS
UNIX FEATURES
SHELL-KERNEL ARCHITECTURE
FILE SYSTEM
1.2 2 UNIX COMMANDS
GENERAL COMMANDS
DIRECTORY COMMANDS
FILE COMMANDS
1.3 3 VI EDITOR
INSERT MODE
COMMAND MODE
EX MODE
1.4 4 FILTER COMMANDS
HEAD/TAIL
CUT/PASTE
SORT
1.5 5 REGULAR EXPRESSION
GREP
EGREP
2 SHELL PROGRAMMING
2.1 6 SIMPLE SHELL PROGRAMS
A SWAPPING TWO VALUES
B CENTIGRADE TO FAHRENHEIT
C AREA OF A CIRCLE
D SIMPLE INTEREST
2.2 7 DECISION MAKING
A ODD OREVEN
B BIGGEST OF 3 NUMBERS
C LEAP YEAR
-
7/28/2019 GE2155 full lab manual
3/81
-
7/28/2019 GE2155 full lab manual
4/81
Ex. No Lab # Name of the experiment Page No
E BASIC CALCULATOR
3.2 12 POINTER PROGRAMMING
A PASS BY VALUE / REFERENCE
B RETURN BY REFERENCE
C SUM OF ARRAY ELEMENTS
D PRINTING 2D ARRAY
E STRING COPY
F STUDENT DETAILS
G PAYROLL PROCESSING
3.3 13 DYNAMIC MEMORY ALLOCATION
A MARKAGGREGATE
B STRING REALLOCATION
C 2D ARRAY ALLOCATION
3.4 14 FILE HANDLING
A WRITE TO FILECHARACTERI/O
B FILE STATISTICS
C EMPLOYEE FILERANDOM ACCESS
3.5 15 COMMAND LINE ARGUMENTS
A ARGUMENT LIST
B FILE COPYCP
C FILE DISPLAYCAT
-
7/28/2019 GE2155 full lab manual
5/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.1 STUDY OF UNIX OPERATING SYSTEM
AIM
To introduce the concept of UNIX Operating System
OPERATING SYSTEM
An Operating System is a set of programs that
Functions as an virtual machine by presenting an interface that is easier to programthan the underlying hardware
Acts as resource management through orderly and controlled allocation of theprocessors, memories, and I/O devices among the programs competing for it.
OS TYPES
1. Single UserThe system will have its own hard disk, memory, CPU and otherresources all dedicated to a single user. Eg. MS-DOS
2. Multi UserThe users having access to a multi-user system will have just a terminaland a keyboard. The other resources such as hard disk, printers are centrally located.The user is expected to simply hook onto his account, perform the work, disconnectand leave quietly. Eg. UNIX
UNIX HISTORY
The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson and
Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information andComputing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in1973 in C principally authored by Ritchie.
UNIX FEATURES
1. Multi-user systemMulti-user capability of UNIX allows several users to use thesame computer to perform their tasks. Several terminals [Keyboards and Monitors]are connected to a single powerful computer [UNIX server] and each user can workwith their terminals.
2. Multi-tasking systemMultitasking is the capability of the operating system toperform various task simultaneously, i.e. a user can run multiple tasks concurrently.
3. Programming FacilityUNIX is highly programmable, the UNIX shell has all thenecessary ingredients like conditional and control structures, etc.
4. SecurityUNIX allows sharing of data; every user must have a single login nameand password. So, accessing another users data is impossible without his permission.
5. PortabilityUNIX is portable because it is written in a high level language. So,UNIX can be run on different computers.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
6/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
6. CommunicationUNIX supports communication between different terminals of thesame server as well as between terminals on different servers.
Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls andLibraries and enhanced GUI (X Window).
ORGANIZATION OF UNIX
The UNIX system is functionally organized at three levels and are:
1. The kernel, which schedules tasks and manages storage;
2. The shell, which connects and interprets users' commands, calls programs frommemory, and executes them; and
3. The tools and applications that offer additional functionality to the OS
UNIX Structure
The kernel is the heart of the system, a collection of programs written in C that directlycommunicate with the hardware. There is only one kernel for any system. It's that part ofUNIX system that is loaded into memory when the system is booted. It manages the systemresources, allocates time between user and processes, decides process priorities, and performsall other tasks. The kernel, in traditional parlance, is often called the Operating system.
The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interfacebetween the user and the kernel. The shell is the agency which takes care of the features ofredirection and has a programming capability of its own.
The Tools and Applications consist of Application Software, Compilers, Database Package,Internet tools, UNIX commands, etc.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
7/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
FILE SYSTEM
A file in UNIX is nothing but a storehouse of information and everything is treated as a fileby UNIX. The files can be broadly classified as follows:
Ordinary filesContains stream of data. All data, text, source programs, object andexecutable code, commands fall into this category.
Directory filesContains no external data. It contains an entry, name of the file andits inode (identification number) for each file and subdirectory under that directory.Directory files are not created by the user but by the UNIX system itself.
Device filesEven physical devices are treated as files. These are special in the sensethat any output directed to it will be reflected onto the respective device.
UNIX File System
All files in UNIX are related to one another. The file system of UNIX resembles a tree thatgrows from top to bottom as shown in the figure. The file system begins with a directorycalled root (at the top). The root directory is denoted by a slash (\). Branching from root thereare several directories such as bin, lib, etc, tmp, dev. Each of these directories containsseveral sub-directories and files.
Result
Thus the study of UNIX Operating System has been completed successfully.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
8/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.2 BASIC COMMANDS
Aim
To study and execute Unix commands.
Unix is security conscious, and can be used only by those persons who have an account.Telnet (Telephone Network) is a Terminal emulator program for TCP/IP networks thatenables users to log on to remote servers.
To logon, type telnet server_ipaddress in run window.
User has to authenticate himself by providing username and password. Once verified, agreeting and$ prompt appears. The shell is now ready to receive commands from the user.Options suffixed with a hyphen () and arguments are separated by space.
General commands
Command Functiondate
Used to display the current system date and time.dat e +%D Displays date onlydat e +%T Displays time onlydat e +%Y Displays the year part of datedat e +%H Displays the hour part of timecal Calendar of the current monthcal year Displays calendar for all months of the specified yearcal month year Displays calendar for the specified month of the yearwho Login details of all users such as their IP, Terminal No, User name,who am i Used to display the login details of the usert t y Used to display the terminal nameuname Displays the Operating System
uname r Shows version number of the OS (kernel).uname n Displays domain name of the serverecho " txt" Displays the given text on the screenecho $HOME Displays the user's home directorybc Basic calculator. Press Ctrl+d to quitl p file Allows the user to spool a job along with others in a print queue.man cmdname Manual for the given command. Press q to exithi story To display the commands used by the user since log on.exi t Exit from a process. If shell is the only process then logs out
Directory commands
Command Functionpwd Path of the present working directorymkdi r dir A directory is created in the given name under the current directory
mkdi r dir1 dir2 A number of sub-directories can be created under one stroke
cd subdir Change Directory. If the subdirstarts with/ then path starts fromroot (absolute) otherwise from current working directory.
cd To switch to the home directory.cd / To switch to the root directory.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
9/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Command Functioncd . . To move back to the parent directoryr mdi r subdir Removes an empty sub-directory.
File commands
Command Functioncat >filename To create a file with some contents. To end typing press Ctrl+d.
The > symbol means redirecting output to a file. (< for input)cat filename Displays the file contents.
cat >>filename Used to append contents to a file
cp src des Copy files to given location. If already exists, it will be overwritten
cpi src des Warns the user prior to overwriting the destination file
cp r src des Copies the entire directory, all its sub-directories and files.
mv old new To rename an existing file or directory. i option can also be used
mv f1 f2 f3 dir To move a group of files to a directory.
mv v old new Display name of each file as it is moved.
r mfile Used to delete a file or group of files. i option can also be usedr m * To delete all the files in the directory.r m r * Deletes all files and sub-directoriesr m f * To forcibly remove even write-protected filesl s Lists all files and subdirectories (blue colored) in sorted manner.l s name To check whether a file or directory exists.l s name* Short-hand notation to list out filenames of a specific pattern.l s a Lists all files including hidden files (files beginning with .)l s x dirname To have specific listing of a directory.l s R Recursive listing of all files in the subdirectoriesl s l Long listing showing file access rights (read/write/execute-rwx for
user/group/others-ugo).cmp file1 file2 Used to compare two files. Displays nothing if files are identical.
wc file It produces a statistics of lines (l), words(w), and characters(c).
chmod perm file Changes permission for the specified file. (r =4, w=2, x=1)chmod 740 file sets all rights for user, read only for groupsand no rights for others
The commands can be combined using the pipeline (| ) operator. For example, number ofusers logged in can be obtained as.
who | wc - l
Finally to terminate the unix session execute the commandexit orlogout.
Result
Thus the study and execution of Unix commands has been completed successfully.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
10/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host vi j ai ] $ dateSat Apr 9 13: 03: 47 I ST 2011
[ vi j ai @l ocal host vi j ai ] $ date +%D04/ 09/ 11
[ vi j ai @l ocal host vi j ai ] $ date +%T13: 05: 33
[ vi j ai @l ocal host vi j ai ] $ date +%Y2011
[ vi j ai @l ocal host vi j ai ] $ date +%H13
[ vi j ai @l ocal host vi j ai ] $ calApr i l 2011
Su Mo Tu We Th Fr Sa
1 23 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
[ vi j ai @l ocal host vi j ai ] $ cal 08 1998August 1998
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 2223 24 25 26 27 28 29
30 31
[ vi j ai @l ocal host vi j ai ] $ cal 18001800
J anuary Febr uar y March
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 1
5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8
12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15
19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22
26 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29
30 31
Oct ober November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 1 2 3 4 5 6
5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
11/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20
19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27
26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31
30
[ vi j ai @l ocal host vi j ai ] $ who
r oot : 0 Apr 9 08: 41vi j ai pt s/ 0 Apr 9 13: 00 ( scl - 64)
cse1 pts/ 3 Apr 9 13: 18 ( scl - 41. smkf omr a. com)
ecea pts/ 4 Apr 9 13: 18 ( scl - 29. smkf omr a. com)
[ vi j ai @l ocal host vi j ai ] $ who am ivi j ai pt s/ 0 Apr 9 13: 00 ( scl - 64)
[ vi j ai @l ocal host vi j ai ] $ tty/ dev/ pt s/ 0
[ vi j ai @l ocal host vi j ai ] $ uname
Li nux
[ vi j ai @l ocal host vi j ai ] $ uname -r2. 4. 20- 8smp
[ vi j ai @l ocal host vi j ai ] $ uname -nl ocal host . l ocal domai n
[ vi j ai @l ocal host vi j ai ] $ echo "How are you"How ar e you
[ vi j ai @l ocal host vi j ai ] $ echo $HOME
/ home/ vi j ai
[ vi j ai @l ocal host vi j ai ] $ echo $USERvi j ai
[ vi j ai @l ocal host vi j ai ] $bcbc 1. 06
Copyr i ght 1991- 1994, 1997, 1998, 2000 Free Sof t ware Foundat i on, I nc.
3+5
8
2%3
2
[ vi j ai @l ocal host l oops] $pwd/ home/ vi j ai / shel l scr i pts/ l oops
[ vi j ai @l ocal host vi j ai ] $mkdir filter
[ vi j ai @l ocal host vi j ai ] $ lsf i l t er l i s t . sh regexpr shel l scr i pt s
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
12/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host vi j ai ] $ cd shellscripts/loops/
[ vi j ai @l ocal host l oops] $
[ vi j ai @l ocal host l oops] $ cd
[ vi j ai @l ocal host vi j ai ] $
[ vi j ai @l ocal host l oops] $ cd /[ vi j ai @l ocal host / ] $
[ vi j ai @l ocal host / ] $ cd /home/vijai/shellscripts/loops/
[ vi j ai @l ocal host l oops] $ cd ..
[ vi j ai @l ocal host shel l scr i pt s]$
[ vi j ai @l ocal host vi j ai ] $ rmdir filter
[ vi j ai @l ocal host vi j ai ] $ lsl i st . sh r egexpr shel l scr i pts
[ vi j ai @l ocal host vi j ai ] $ cat > greethi ece- a
wi shi ng u t he best
[ vi j ai @l ocal host vi j ai ] $ cat greethi ece- a
wi shi ng u t he best
[ vi j ai @l ocal host vi j ai ] $ cat >> greetbye
[ vi j ai @l ocal host vi j ai ] $ cat greethi ece- a
wi shi ng u t he bestbye
[ vi j ai @l ocal host vi j ai ] $ lsgr eet l i st . sh regexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls -a. . bash_l ogout . canna . gt krc r egexpr . vi mi nf o. t mp
. . . bash_pr of i l e . emacs . kde shel l scri pt s . xemacs
. bash_hi st ory . bashr c greet l i st . sh . vi mi nf o
[ vi j ai @l ocal host vi j ai ] $ ls -l
t ot al 16- r w- r w- r - - 1 vi j ai vi j ai 32 Apr 11 14: 52 greet
- r w- rw- r- - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
dr wxrwxr - x 2 vi j ai vi j ai 4096 Apr 9 14: 30 r egexpr
dr wxr wxr - x 7 vi j ai vi j ai 4096 Apr 4 14: 57 shel l scri pt s
[ vi j ai @l ocal host vi j ai ] $ cp greet ./regexpr/
[ vi j ai @l ocal host vi j ai ] $ ls
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
13/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
gr eet l i st . sh regexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls ./regexprdemo gr eet
[ vi j ai @l ocal host vi j ai ] $ cp -i greet ./regexpr/cp: over wr i t e ' greet ' ? n
[ vi j ai @l ocal host vi j ai ] $mv greet greet.txt
[ vi j ai @l ocal host vi j ai ] $ lsgr eet . t xt l i st . sh regexpr shel l scr i pts
[ vi j ai @l ocal host vi j ai ] $mv greet.txt ./regexpr/
[ vi j ai @l ocal host vi j ai ] $ ls
l i s t . sh regexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ ls ./regexpr/demo gr eet . t xt
[ vi j ai @l ocal host vi j ai ] $ ls
f act. sh l i st . sh pr i me. sh r egexpr shel l scri pt s
[ vi j ai @l ocal host vi j ai ] $ rm -i *.shr m: r emove r egul ar f i l e ' f act . sh' ? y
rm: r emove r egul ar f i l e ' l i st . sh' ? n
r m: r emove regul ar f i l e ' pr i me. sh' ? y
[ vi j ai @l ocal host vi j ai ] $ ls
l i s t . sh regexpr shel l scr i pt s
[ vi j ai @l ocal host vi j ai ] $ wc list.sh4 9 30 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ wc -l list.sh4 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ cmp list.sh fact.shl i s t . sh f act . sh di f f er : byt e 1, l i ne 1
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh- r w- rw- r- - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ chmod ug+x list.sh
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh- r wxr wxr - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
[ vi j ai @l ocal host vi j ai ] $ chmod 740 list.sh
[ vi j ai @l ocal host vi j ai ] $ ls -l list.sh- r wxr- - - - - 1 vi j ai vi j ai 30 Apr 4 13: 58 l i st . sh
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
14/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.3 STUDY OF VI EDITOR
Aim
To introduce the concept of text editing vi editor and the options regarding the controlof the editor.
vi Editor
A text editor is one of the most common and useful tools in all Operating Systems.Unix provides a versatile editorvi, a full-screen editor and owes its origin to Bill Joy. "vi"stands forvisual editor. A vi session begins by invoking vi with or without a filename
$vi
$vi filename
The user is presented with a full empty screen, each line beginning with a ~. This is vi's wayof indicating non-existent lines. Out of 25 lines on the terminal, 24 can be used to enter text.The last line is reserved for commands and also used by the system to display messages. vi
functions in three modes namely:1. Input modeWhere any key depressed is entered as text2. Command modeWhere keys are used as commands to act on text (initial mode)3. ex modeex mode commands that can be entered in the last line to act on text
vi modes
INPUT MODE
vi starts with command mode. To insert text any of the following commands should be used.
Commands Function
i Inserts text to the left of the cursor.I Inserts text at the beginning of line.a Appends text to right of cursorA Appends text at end of lineo Opens line belowO Opens line above
In Inputmode the editor displays INSERT in the last line. Press Enterkey to start a fresh lineof text in Input mode and the ~ disappears. To quit inputmode press Esc key.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
15/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
COMMAND MODE
EDIT COMMANDS
Command FunctionR Replaces more than a single character. The editor displays REPLACE in
the last line. The existing text is overwritten as they are typed.s Deletes a single character to the left and switches to Input mode.x Deletes the character in the current cursor position?text Locates the text in the file. If not found, the message "Pattern not found"
appears. Use n to repeat the forward search andN for backward search.U or u Reverses the last change made to the buffer.dd Cuts the entire linedw Cuts the entire wordd$ Cuts a line from cursor position to the end of the lined0 Cuts from the cursor position to the start of the lineyy Copies (yanks) the entire line
yw Copies the entire wordp Pastes the text
NAVIGATION COMMANDS
Command Functionb Moves back to beginning of a wordw Moves forward to beginning of word| Moves to start of the line$ Moves to end of the linek Up one line
j Down one lineh Left one characterl Right one characterCt r l +f Scrolls a page forwardCt r l +b Scrolls a page backwardlG To move to the specific line
One of the most notable features of vi is the facility of prefixing a number to mostcommands. When prefixed, commands interpret the instruction to be repeated as many times.For example 3x deletes the next three character.
THE EX MODE
The essential save and exit commands form the features of ex mode. Press : (colon) incommand mode to switch to ex mode. The : is displayed in the last line. Type the commandand press Enterkey to execute the same.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
16/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Command Functionw Saves file, displays the number of lines & characters and returns to
Input mode. If it is an unnamed file then vi puts a message.w file The file is saved under the given name
L1,L2 wfile Used to write specific line numbers to some file. The . (dot) represents
current line, 0 for first line and$ could be used to represent last line.q Quits vi session and returns to $ prompt. vi has a safety mechanism
that warns if changes made to file are not saved.q! Quits vi session without saving any changes made since the last savewq Save and exitsh Escape to shell%s/ Sstr/ Rstr/ g This is yet another powerful feature known as substitution. It is
similar to Find and Replace. % represents all lines, g makes it global.To make vi ask for confirmation before replacing use gc instead ofg.
r file To insert another file into the current file.
new file Splits screen into multiple windows and opens the file.
vi editor
vi Editor
ResultThus the study of text manipulation using vi editor has been completed successfully.
This is vi improved vimA rudimentary text~~~~~~~~~Sample.txt 2L, 30C written
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
17/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.4 Simple Filters
AimTo query a data file using filter commands in unix.
Filters are the central commands of the UNIX tool kit. It acts on data file where lines are
records, fields delimited by a character not used by the data (mostly |, default is white space).The output is a set of records and the input file is unaltered by these commands.
Command Functionheadused to display the first few records (10 records by default)head st ud Displays first 10 records by defaulthead - 5 st ud Displays first 5 recordshead - 1 st ud | wc c length of first recordtailused to display the last few records (10 records by default)tai l stud Displays last 10 records by defaultt ai l - 5 stud | t ee l ast5 Last 5 records listed & stored in file last5 using tee
cut
used to extract specific fields. The d option specifies the delimiter and f forspecifying the field list. The c option may be used if extraction is done character wisecut d \ | - f 1, 3, 4 stud Fields 1,3,4 listedcut d \ | - f 2- 4 stud Fields 2,3,4 listedpast e d \ | l i st1 l i st2 merges two cut files list1 andlist2sortreorders the file as per ASCII sequence. The t option is used to specify delimiter andk option to specify the fieldsort stud Sorted on 1st column by defaultsort t \ | - k 3 stud Sort as per 3rdcolumnsor t c st ud Check if file is sorted using c optionsor t - t \ | - k 4, 4 - k 3, 3st ud
Sorting on secondary keys
sort - t \ | - nr k 4 stud Sort on numeric field using n option, r for reverseuni q st ud Display unique entries in a sorted filetrtranslates characters. Can be used to change text case. It works with standard input nameorg[ vi j ai @l ocal host f i l t ers ]$ cut -d \| -f 5 stud > sal
[ vi j ai @l ocal host f i l t ers ]$paste -d \| nameorg salAart hi | CTS | 36000
Al ber t J er r y | Wi pr o | 25000
Ar un | Ramco | 12000
Di wakar | TCS | 10500
Geet ha | I nf osys | 23000
I r udayar aj | Pol ar i s | 30000
J aya Pr akash | Ramco | 28000
Mahesh | Mi cr osof t | 5000
Mani maran | Mi cr osof t | 9000Mohammed Mukt har | Or acl e | 6000
Pr i t hi vi Raj an | Ramco | 25000
Pushpak Chander | CTS | 27500
Ramesh | Wi pro | 24000
Smi t ha | Ramco | 30000
Sr i Gur umoor t hy | Mi cr osof t | 11000
Tami l Sel vi | CTS | 3500
Thamot haran | CTS | 9000
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
20/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host f i l t ers ]$ sort stud20057702| Al bert J err y | CSE | Wi pro | 25000
20057705| Geet ha | CSE | I nf osys | 23000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 2750020057713| Ramesh | CSE | Wi pr o | 24000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamothar an | I T | CTS | 9000
20057801| Aart hi | ECE | CTS | 36000
20057806| I r udayaraj | ECE | Pol ari s | 30000
20057817| Smi t ha | ECE | Ramco | 30000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
[ vi j ai @l ocal host f i l t ers ]$ sort -t \| -k 1 stud20057801| Aart hi | ECE | CTS | 36000
20057702| Al bert J err y | CSE | Wi pro | 25000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057705| Geet ha | CSE | I nf osys | 23000
20057806| I r udayaraj | ECE | Pol ari s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057909| Mani mar an | I T | Mi cr osof t | 900020058010| Mohammed Mukt har | EEE | Or acl e | 6000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057712| Pushpak Chander | CSE | CTS | 27500
20057713| Ramesh | CSE | Wi pr o | 24000
20057817| Smi t ha | ECE | Ramco | 30000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamothar an | I T | CTS | 9000
[ vi j ai @l ocal host f i l t ers ]$ sort -t \| -k 4,4 -k 3,3 stud20057712| Pushpak Chander | CSE | CTS | 27500
20057801| Aart hi | ECE | CTS | 36000
20057719| Tami l Sel vi | EEE | CTS | 3500
20057720| Thamothar an | I T | CTS | 9000
20057705| Geet ha | CSE | I nf osys | 23000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057909| Mani mar an | I T | Mi cr osof t | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
21/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
20057806| I r udayaraj | ECE | Pol ari s | 30000
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057817| Smi t ha | ECE | Ramco | 30000
20057903| Ar un | I T | Ramco | 12000
20057904| Di wakar | I T | TCS | 10500
20057713| Ramesh | CSE | Wi pr o | 2400020057702| Al bert J err y | CSE | Wi pro | 25000
[ vi j ai @l ocal host f i l t ers ]$ sort -t \| -nr -k 5 stud20057801| Aart hi | ECE | CTS | 36000
20057817| Smi t ha | ECE | Ramco | 30000
20057806| I r udayaraj | ECE | Pol ari s | 30000
20057707| J aya Pr akash | CSE | Ramco | 28000
20057712| Pushpak Chander | CSE | CTS | 27500
20057711| Pr i t hi vi Raj an | CSE | Ramco | 25000
20057702| Al bert J err y | CSE | Wi pro | 25000
20057713| Ramesh | CSE | Wi pr o | 24000
20057705| Geet ha | CSE | I nf osys | 23000
20057903| Ar un | I T | Ramco | 12000
20057718| Sr i Gur umoor t hy | I T | Mi cr osof t | 11000
20057904| Di wakar | I T | TCS | 10500
20057909| Mani mar an | I T | Mi cr osof t | 9000
20057720| Thamothar an | I T | CTS | 9000
20058010| Mohammed Mukt har | EEE | Or acl e | 6000
20058008| Mahesh | EEE | Mi cr osof t | 5000
20057719| Tami l Sel vi | EEE | CTS | 3500
[ vi j ai @l ocal host f i l t ers ]$ tr '[a-z]' '[A-Z]' < stud
20057801| AARTHI | ECE | CTS | 3600020057702| ALBERT J ERRY | CSE | WI PRO | 25000
20057903| ARUN | I T | RAMCO | 12000
20057904| DI WAKAR | I T | TCS | 10500
20057705| GEETHA | CSE | I NFOSYS | 23000
20057806| I RUDAYARAJ | ECE | POLARI S | 30000
20057707| J AYA PRAKASH | CSE | RAMCO | 28000
20058008| MAHESH | EEE | MI CROSOFT | 5000
20057909| MANI MARAN | I T | MI CROSOFT | 9000
20058010| MOHAMMED MUKTHAR | EEE | ORACLE | 6000
20057711| PRI THI VI RAJ AN | CSE | RAMCO | 25000
20057712| PUSHPAK CHANDER | CSE | CTS | 2750020057713| RAMESH | CSE | WI PRO | 24000
20057817| SMI THA | ECE | RAMCO | 30000
20057718| SRI GURUMOORTHY | I T | MI CROSOFT | 11000
20057719| TAMI L SELVI | EEE | CTS | 3500
20057720| THAMOTHARAN | I T | CTS | 9000
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
22/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 1.5 Regular Expression
AimTo search for regular expression in a file using grep command in unix.
A frequent requirement is to look for a pattern or expression in a file. Unix handles
this feature through grep and egrep. grep uses an regular expression to display lines thatmatch andegrep enables searching for multiple patterns. Its usage is
gr ep options searchtext filename
Command Functiongrep t hi s demo Lists the lines that contains the string thisgr ep ' end of ' demo Quotes mandatory for text containing spacegrep t hi s demo* Search this in multiple filesgrep c t o demo Number of occurrence of the wordto in the filegr ep n sequence demo Display line numbers along with matching lines
gr ep v wor d demo Displays lines that does not contain the text wordgr ep l vi m * Displays files containing text vimgr ep i WORD demo Search for text ignoring case differencesgr ep ' [ 0- 9] ' demo Lines that start with a numbergr ep ' [ 0- 9] $' demo Lines that end with a numberl s - l | gr ep " d" Display the subdirectory namesgr ep c " $" demo Display count of blank lines in the file.gr ep "2. . . . $" st ud Display lines that ends in the range 2000029999egr ep "l ower | UPPER" demo Display lines that match eitherlowerorupperegr ep "( pr evi ous| cur r ent )wor d" demo
Display lines that match either previous wordorcurrent word
Result
Thus searching text patterns in files using grep has been completed successfully.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
23/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
demo file
[ vi j ai @l ocal host r egexpr ] $ grep this demot hi s l i ne i s the 1st l ower case l i ne i n t hi s f i l e.Two l i nes above t hi s l i ne i s empt y.
[ vi j ai @l ocal host r egexpr ] $ grep 'end of' demo1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he curr ent WORD.
[ vi j ai @l ocal host r egexpr ] $ grep -c to demo5
[ vi j ai @l ocal host r egexpr ] $ grep -n sequence demo15: WORD - WORD consi st s of a sequence of non- bl ank charact ers
16: Word - wor d consi st s of a sequence of l et t er s, di gi t s and underscor es.
[ vi j ai @l ocal host r egexpr ] $ grep -v word demoTHI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.
t hi s l i ne i s the 1st l ower case l i ne i n t hi s f i l e.
Thi s Li ne Has Al l I t s Fi r st Charact er Of The Wor d Wi t h Upper Case.
Two l i nes above t hi s l i ne i s empt y.
vi m Word Navi gat i on
2. E - go t o t he end of t he curr ent WORD.
4. B - go to t he previ ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank charact er s
t el net 172. 16. 4. 256
THI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.t hi s l i ne i s the 1st l ower case l i ne i n t hi s f i l e.Thi s Li ne Has Al l I t s Fi r st Charact er Of The Wor d Wi t h Upper Case.
Two l i nes above t hi s l i ne i s empt y.vi m Word Navi gat i on
You may want t o do several navi gat i on i n r el at i on t o wor ds, such as:
1. e - go to t he end of t he cur r ent word.2. E - go t o t he end of t he cur r ent WORD.3. b - go t o t he pr evi ous word.4. B - go to t he previ ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank char act ersWord - wor d consi st s of a sequence of l et t er s, di gi t s and underscor es.
t el net 172. 16. 4. 256
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
24/81
Unix Commands GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
[ vi j ai @l ocal host r egexpr ] $ grep -l vim *demo r eadme
[ vi j ai @l ocal host r egexpr ] $ grep -i WORD demoThi s Li ne Has Al l I t s Fi r st Charact er Of The Wor d Wi t h Upper Case.
vi m Wor d Navi gati on
You may want t o do sever al navi gat i on i n r el at i on t o wor ds, such as:1. e - go to the end of t he cur r ent word.
2. E - go t o the end of t he cur r ent WORD.
3. b - go t o the pr evi ous word.
4. B - go t o t he pr evi ous WORD.
WORD - WORD consi st s of a sequence of non- bl ank charact ers
Wor d - word consi st s of a sequence of l et t ers , di gi t s and under scores.
[ vi j ai @l ocal host r egexpr ] $ grep '^[0-9]' demo1. e - go t o t he end of t he cur r ent wor d.
2. E - go t o t he end of t he curr ent WORD.
3. b - go t o the pr evi ous word.
4. B - go to t he previ ous WORD.
[ vi j ai @l ocal host r egexpr ] $ grep '[0-9]$' demot el net 172. 16. 4. 256
[ vi j ai @l ocal host vi j ai ] $ ls -l | grep "^d"dr wxrwxr - x 2 vi j ai vi j ai 4096 Apr 9 14: 30 r egexpr
dr wxr wxr - x 7 vi j ai vi j ai 4096 Apr 4 14: 57 shel l scri pt s
[ vi j ai @l ocal host r egexpr ] $ grep -c "^$" demo5
[ vi j ai @l ocal host r egexpr ] $ egrep "lower|UPPER" demoTHI S LI NE I S THE 1ST UPPER CASE LI NE I N THI S FI LE.
t hi s l i ne i s the 1st l ower case l i ne i n t hi s f i l e.
[ vi j ai @l ocal host r egexpr ] $ egrep "(previous|current) word" demo
1. e - go t o t he end of t he cur r ent wor d.
3. b - go t o the pr evi ous word.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
25/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.1 SIMPLE PROGRAMS
Aim
To write simple shell programs using shell programming fundamentals.
The activities of a shell are not restricted to command interpretation alone. The shell also has
rudimentary programming features. When a group of commands has to be executed regularly,they are stored in a file (with extension .sh). All such files are called shell scripts or shell
programs. Shell programs run in interpretive mode.
The original UNIX came with the Bourne shell (sh) and it is universal even today. Then
came a plethora of shells offering new features. Two of them, C shell (csh) and Korn shell
(ksh) has been well accepted by the UNIX fraternity. Linux offers Bash shell (bash) as a
superior alternative to Bourne shell.
Preliminaries
1. Comments in shell script start with #. It can be placed anywhere in a line; the shell
ignores contents to its right. Comments are recommended but not mandatory
2. Shell variables are loosely typed i.e. not declared. Their type depends on the value
assigned. Variables when used in an expression or output must be prefixed by $.
3. The readstatement is shell's internal tool for making scripts interactive.
4. Output is displayed using echo statement. Any text should be within quotes. Escape
sequence should be used with e option.
5. Commands are always enclosed with ` ` (back quotes).
6. Expressions are computed using the expr command. Arithmetic operators are + -* / %. Meta characters * ( ) should be escaped with a \.
7. Multiple statements can be written in a single line separated by ;
8. The shell scripts are executed using the sh command (shfilename).
Result
Thus using programming basics, simple shell scripts were executed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
26/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.1.ASwapping values of two variables
Algorithm
Step 1 : Start
Step 2 : Read the values of a andb
Step 3 : Interchange the values ofa andb using another variable tas follows:
t= a
a = b
b = t
Step 4 : Print a andb
Step 5 : Stop
Program (swap.sh)
# Swappi ng val uesecho - n "Ent er val ue f or A : "r ead aecho - n "Ent er val ue f or B : "
r ead bt =$aa=$bb=$techo "Val ues af t er Swappi ng"echo "A Val ue i s $a"echo "B Val ue i s $b"
Output
[ vi j ai @l ocal host si mpl e] $ sh swap.shEnt er val ue f or A : 12Ent er val ue f or B : 23Val ues af t er Swappi ngA Val ue i s 23B Val ue i s 12
2.1.BFarenheit to Centigrade Conversion
Algorithm
Step 1 : Start
Step 2 : Read fahrenheitvalue
Step 3 : Convert fahrenheitto centigrade using the formulae: (fahrenheit 32) 5/9Step 4 : Print centigradeStep 5 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
27/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (degconv.sh)
# Degr ee conver si onecho - n "Ent er Fahr enhei t : "r ead fc= expr \ ( $f - 32 \ ) \ * 5 / 9`echo "Cent i gr ade i s : $c"
Output
[ vi j ai @l ocal host si mpl e] $ sh degconv.shEnt er Fahr enhei t : 213Cent i gr ade i s : 100
2.1.C Area & Circumference of Circle
Algorithm
Step 1 : StartStep 2 : Define constant pi = 3.14
Step 3 : Read the value of radiusStep 4 : Calculate area using formulae: pi radius2
Step 5 : Calculate circumference using formulae: 2 pi radiusStep 6 : Print area andcircumference
Step 7 : Stop
Program (circle.sh)
# Ci r cl e met r i cs usi ng r eadonl y var i abl epi = expr "scal e=2; 22 / 7" | bc`
r eadonl y pi # pi val ue cannot be al t er edecho - n "Ent er val ue f or r adi us : "r ead r adi usar ea= expr "scal e=2; $pi * $r adi us * $r adi us" | bc`ci r cum= expr "scal e=2; 2 * $pi * $radi us" | bc`echo "Ar ea : $ar ea"echo "Ci r cumf er ence : $ci r cum"
Output
[ vi j ai @l ocal host si mpl e] $ sh circle.shEnt er val ue f or r adi us : 12Ar ea : 452. 16Ci r cumf erence : 75. 36
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
28/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.1.D Simple Interest Calculation
Algorithm
Step 1 : Start
Step 2 : Read the values principal, rate andyears
Step 3 : Compute simpleinterestusing the formulae: (principal rate years) / 100
Step 4 : Print simpleinterest
Step 5 : Stop
Program (simpint.sh)
# I nt er est comput at i on usi ng bcecho - n "Ent er Pr i nci pal amount : "r ead pecho - n "Ent er number of year s : "r ead necho - n "Ent er r at e of i nt er est : "r ead r
si = expr "scal e=2; $p * $n *$r / 100" | bc`echo "Si mpl e I nt er est : $si "
Output
[ vi j ai @l ocal host si mpl e] $ sh simpint.shEnt er Pr i nci pal amount : 1285Ent er number of years : 3Ent er r at e of i nt er est : 5Si mpl e I nt er est : 192. 75
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
29/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.2 CONDITIONAL STATEMENT
Aim
To write shell programs using decision-making constructs.
Shell supports decision-making using if statement. The if statement like its counterpart in
programming languages has the following formats. The first construct executes thestatements when the condition is true. The second construct adds an optional else to the
first one that has different set of statements to be executed depending on whether the
condition is true or false. The last one is an elif ladder, in which conditions are tested insequence, but only one set of statements is executed.
i f [ condition ]t hen
statementsf i
i f [ condition ]t hen
statementsel se
statementsf i
i f [ condition ]t hen
statements
el i f [ condition ]t hen
statements.. .
el sestatements
f i
The set of relational and logical operators used in conditional expression is given below. The
numeric comparison in the shell is confined to integer values only.
Operator Description- eq Equal to- ne Not equal to- gt Greater than- ge Greater than or equal to- l t Less than- l e Less than or equal to- a Logical AND- o Logical OR! Logical NOT
ResultThus using if statement scripts with conditional expressions were executed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
30/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.2.A Odd or even
Algorithm
Step 1 : Start
Step 2 : Read number
Step 3 : If numberdivisible by 2 then
Print "Number is Even"
Step 3.1 : else
Print "Number is Odd"
Step 4 : Stop
Program (oddeven.sh)
# Odd or even usi ng i f - el seecho - n "Ent er a non- zer o number : "r ead numr em= expr $num% 2`i f [ $r em - eq 0 ]
t henecho "$num i s Even"
el seecho "$num i s Odd"
f i
Output
[ vi j ai @l ocal host deci si on] $ sh oddeven.shEnt er a non- zero number : 1212 i s Even
2.2.BBiggest of 3 numbers
Algorithm
Step 1 : Start
Step 2 : Read values ofa, b andc
Step 3 : If a > b anda > c thenPrint "A is the biggest"
Step 3.1 : else if b > c thenPrint "B is the biggest "
Step 3.2 : else
Print "C is the biggest"Step 4 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
31/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (big3.sh)
# Bi ggest usi ng l ogi cal expr essi onecho - n "Gi ve val ue f or A B and C: "r ead a b ci f [ $a - gt $b - a $a - gt $c ]t hen
echo "A i s t he Bi ggest number"el i f [ $b - gt $c ]t hen
echo "B i s t he Bi ggest number"el se
echo "C i s t he Bi ggest number"f i
Output
[ vi j ai @l ocal host deci si on] $ sh big3.shGi ve val ue f or A B and C: 4 3 4
C i s t he Bi ggest number
2.2.CLeap year
Algorithm
Step 1 : Start
Step 2 : Read the value ofyear
Step 3 : If yeardivisible by 400 thenPrint "Leap year"
Step 3.1 : else if yeardivisible by 4 and not divisible by 100 thenPrint "Leap year"
Step 3.2 : elsePrint "Not a leap year"
Step 4 : Stop
Program (leap.sh)
# Leap yearecho - n "Ent er a year : "r ead yearr em1= expr $year % 4`r em2= expr $year % 100`r em3= expr $year % 400`
i f [ $r em3 - eq 0 ]t henecho "$year i s a Leap Year "
el i f [ $r em2 - ne 0 - a $r em1 - eq 0 ]t hen
echo "$year i s a Leap Year "el se
echo "$year i s Not a l eap year "f i
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
32/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host deci si on] $ sh leap.shEnt er a year : 19001900 i s Not a l eap year
2.2.DGrade Determination
Algorithm
Step 1 : Start
Step 2 : Read mark
Step 3 : Ifmark> 90 then
Print "S grade"
Step 3.1 : else ifmark> 80 then
Print "A grade"
Step 3.2 : else ifmark> 70 then
Print "B grade"
Step 3.3 : else ifmark> 60 thenPrint "C grade"
Step 3.4 : else ifmark> 55 then
Print "D grade"Step 3.5 : else ifmark 50 then
Print "E grade"
Step 3.6 : else
Print "U grade"
Step 4 : Stop
Program (grade.sh)
echo - n "Ent er t he mark : "r ead mar ki f [ $mark - gt 90 ]t hen
echo "S Gr ade"el i f [ $mar k - gt 80 ]t hen
echo "A Gr ade"el i f [ $mar k - gt 70 ]t hen
echo "B Gr ade"el i f [ $mar k - gt 60 ]
t henecho "C Gr ade"el i f [ $mar k - gt 55 ]t hen
echo " D Gr ade"
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
33/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
el i f [ $mar k - ge 50 ]t hen
echo "E Gr ade"el se
echo "U Gr ade"f i
Output
[ vi j ai @l ocal host deci si on] $ sh grade.shEnt er t he mark : 65C Gr ade
2.2.EString comparison
Algorithm
Step 1 : Start
Step 2 : Read strings str1 andstr2Step 3 : If str1 = str2 then
Print "Strings are the same"
Step 3.1 : elsePrint "Strings are distinct"
Step 4 : Stop
Program (strcomp.sh)
echo - n "Ent er t he f i r st st r i ng : "r ead s1echo - n "Ent er t he second st r i ng : "r ead s2i f [ $s1 == $s2 ]t henecho "St r i ngs are t he same"el seecho "St r i ngs ar e di st i nct "f i
Output
[ vi j ai @l ocal host deci si on] $ sh strcomp.shEnt er t he f i r st st r i ng : ece- aEnt er t he second st r i ng : ECE- A
St r i ngs ar e di st i nct
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
34/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.2.FEmployee Pay Calculation
Algorithm
Step 1 : Start
Step 2 : Read basic
Step 3 : Ifbasic > 30000 then
hra is 5% ofbasic
da is 5% ofbasic
tax is 10% ofbasic
Step 3.1 : else ifbasic > 20000 then
hra is 4% ofbasic
da is 3% ofbasic
tax is 8% ofbasic
Step 3.2 : else
hra is 3% ofbasic
da is 2% ofbasic
tax is 5% ofbasic
Step 4 : Stop
Program (emppay.sh)
echo - n "Ent er empl oyee basi c pay : "r ead basi ci f [ $basi c - gt 30000 ]t hen
hr a= expr 5 \ * $basi c / 100`da= expr 5 \ * $basi c / 100`t ax= expr 10 \ * $basi c / 100`
el i f [ $basi c - gt 20000 ]t hen
hr a= expr 4 \ * $basi c / 100`da= expr 3 \ * $basi c / 100`t ax= expr 8 \ * $basi c / 100`
el sehr a= expr 3 \ * $basi c / 100`da= expr 2 \ * $basi c / 100`t ax= expr 5 \ * $basi c / 100`
f igr oss= expr $basi c + $da + $hr a`net pay= expr $gr oss - $t ax`echo "Gr oss Pay : $gr oss"echo "Net Pay : $net pay"
Output
[ vi j ai @l ocal host deci si on] $ sh emppay.shEnt er empl oyee basi c pay : 12000Gr oss Pay : 12600Net Pay : 12000
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
35/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.3 MULTI-WAY BRANCHING
Aim
To write shell programs using case construct to match patterns.
The case statement is used to compare a variables value against a set of constants (integer,
character, string, range). If it matches a constant, then the set of statements followed after) isexecuted till a ; ; is encountered. The optional default block is indicated by *. Multipleconstants can be specified in a single pattern separated by |.
case variable i nconstant1)
statements ; ;constant2)
statements ; ;. . .
constantN)
statements ; ;
*)statementsesac
Result
Thus using case statement, shell scripts were executed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
36/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.3.AVowel or Consonant
Algorithm
Step 1 : Start
Step 2 : Read char
Step 3 : If charis either 'a', 'e', 'i', 'o' or 'u' then
Print "It's a vowel"
Step 3.1 : else
Print "It's a consonant"
Step 4 : Stop
Program (vowel.sh)
# Vowel wi t h mul t i pl e val ues i n a pat t er necho - n "Key i n a l ower case char acter : "r ead choi cecase $choi ce i n
a| e| i | o| u) echo "I t ' s a Vowel "; ;
*) echo "I t ' s a Consonant "esac
Output
[ vi j ai @l ocal host mul t way] $ sh vowel.cKey i n a l ower case charact er : eI t ' s a Vowel
2.3.BSimple Calculator
Algorithm
Step 1 : Start
Step 2 : Read operands a andbStep 3 : Display operation menu
Step 4 : Read optionStep 5 : If option = 1 then
Calculate c = a + bStep 5.1 : else ifoption = 2 then
Calculate c = abStep 5.2 : else ifoption = 3 then
Calculate c = a * b
Step 5.3 : else ifoption = 4 thenCalculate c = a / b
Step 5.4 : else ifoption = 5 then
Calculate c = a % b
Step 5.5 : else
Print "Invalid option"
Step 6 : Print c
Step 7 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
37/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (calc.sh)
# Ar i t hmet i c oper at i ons- - mul t i pl e st at ement s i n a bl ockecho - n "Ent er t he two number s : "r ead a becho " 1. Addi t i on"echo " 2. Subt r act i on"
echo " 3. Mul t i pl i cat i on"echo " 4. Di vi si on"echo " 5. Modul o Di vi si on"echo - n "Ent er t he opt i on : "r ead opt i oncase $opt i on i n
1) c= expr $a + $b`echo "$a + $b = $c" ; ;
2) c= expr $a - $becho "$a - $b = $c"; ;
3) c= expr $a \ * $b`echo "$a * $b = $c"; ;
4) c= expr $a / $becho "$a / $b = $c"; ;
5) c= expr $a % $becho "$a % $b = $c"; ;
*) echo "I nval i d Opt i on"esac
Output
[ vi j ai @l ocal host mul t way] $ sh calc.shEnt er t he t wo number s : 2 41. Addi t i on
2. Subt r act i on3. Mul t i pl i cat i on4. Di vi s i on5. Modul o Di vi si on
Ent er t he opt i on : 12 + 4 = 6
2.3.CRental Options
Algorithm
Step 1 : Start
Step 2 : ReadvehicleStep 3 : If vehicle = "car" then
Print "Rental is Rs. 20/km"
Step 3.1 : else if vehicle = "van" thenPrint "Rental is Rs. 10/km"
Step 3.2 : else if vehicle = "jeep" then
Print "Rental is Rs. 5/km"
Step 3.3 : else if vehicle = "bicycle" then
Print "Rental is Rs. 0.2/km"
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
38/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Step 3.4 : else
Print "Vehicle not available"
Step 4 : Stop
Program (rental.sh)
# Str i ng matchi ngecho "Two/ Four wheel er r ent al "echo - n "Ent er t he r equi r ed vehi cl e : "r ead vehi cl ecase $vehi cl e i n
"car ") echo "For $vehi cl e Rs. 20 per km"; ;"van") echo "For $vehi cl e Rs. 10 per km"; ;
" j eep") echo "For $vehi cl e Rs. 5 per km" ; ;"bi cycl e" ) echo "For $vehi cl e 20 pai sa per km"; ;
*) echo "Sor r y, I cannot get a $vehi cl e f or you"; ;esac
Output
[ vi j ai @l ocal host mul t way] $ sh rental.shTwo/ Four wheel er r ent alEnt er t he r equi r ed vehi cl e : bi cycl eFor bi cycl e 20 pai sa per km
2.3.DVote Eligibility (vote.sh)
Algorithm
Step 1 : StartStep 2 : Readage
Step 3 : If age 17Print "Not eligible to vote"
Step 3.1 : elsePrint "Eligible to vote"
Step 4 : Stop
Program
# Vote- - r ange matchi ngecho - n "Ent er your age : "r ead agecase $age i n
[ 0- 9] | 1[ 0- 7] ) echo "You ar e not el i gi bl e t o vot e"; ;*) echo "El i gi bl e t o vot e"esac
Output
[ vi j ai @l ocal host mul t way] $ sh vote.shEnt er your age : 12
You ar e not el i gi bl e t o vot e
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
39/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.4 LOOPS
Aim
To write shell programs using different types of loops.
Shell supports a set of loops such as for, while anduntil to execute a set of statements
repeatedly. The body of the loop is contained between do anddone statement.
The for loop doesn't test a condition, but uses a list instead.
f or variable i n listdo
statementsdone
The while loop executes the statements as long as the condition remains true.
whi l e [ condition ]do
statementsdone
The until loop complements the while construct in the sense that the statements are executed
as long as the condition remains false.
unt i l [ condition ]do
statementsdone
ResultThus using loops, iterative scripts were executed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
40/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.4.AMultiplication Table
Algorithm
Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize 1 to i
Step 4 : Print n, i, ni
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5 until i 10
Step 7 : Stop
Program (multable.sh)
# Mul t i pl i cat i on t abl e usi ng f or l oopcl earecho - n "Whi ch mul t i pl i cat i on t abl e? : "r ead nf or x i n 1 2 3 4 5 6 7 8 9 10
dop= expr $x \ * $n`echo - n "$n X $x = $p"sl eep 1
done
Output
[ vi j ai @l ocal host l oops] $ sh multable.shWhi ch mul t i pl i cat i on t abl e? : 66 X 1 = 66 X 2 = 126 X 3 = 186 X 4 = 246 X 5 = 306 X 6 = 366 X 7 = 426 X 8 = 486 X 9 = 546 X 10= 60
2.4.BArmstrong Number
Algorithm
Step 1 : Start
Step 2 : Read number
Step 3 : Initialize 0 to sum andnumberto num
Step 4 : Extract lastdigitby computing numbermodulo 10
Step 5 : Cube the lastdigitand add it to sum
Step 6 : Divide numberby 10
Step 7: Repeat steps 46 until number> 0
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
41/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Step 8 : Ifsum = numberthen
Print Armstrong number
Step 8.1 : else
Print Not an Armstrong number
Step 9 : Stop
Program (armstrong.sh)
# Ar mst r ong number usi ng whi l e l oopecho - n "Ent er a number : "r ead na=$ns=0whi l e [ $n - gt 0 ]do
r = expr $n % 10`s= expr $s + \ ( $r \ * $r \ * $r \ ) `n= expr $n / 10`
donei f [ $a - eq $s ]t hen
echo "Ar mst r ong Number"el se
echo - n "Not an Ar mst r ong number"f i
Output
[ vi j ai @l ocal host l oops] $ sh armstrong.shEnt er a number : 370Armst r ong Number
2.4.CNumber Reverse
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : Initialize 0 to reverse
Step 4 : Extract lastdigitby computing numbermodulo 10Step 5 : Compute reverse = reverse
10+ lastdigit
Step 6 : Divide numberby 10Step 7: Repeat steps 46 until number> 0
Step 8 : Print reverseStep 9 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
42/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (reverse.sh)
# To reverse a number usi ng whi l e l oopecho - n "Ent er a number : "r ead nr d=0whi l e [ $n - gt 0 ]
dor em= expr $n % 10`r d= expr $r d \ * 10 + $r emn= expr $n / 10`
doneecho "Rever sed number i s $r d"
Output
[ vi j ai @l ocal host l oops] $ sh reverse.shEnt er a number : 234Reversed number i s 432
2.4.DFibonacci Series
Algorithm
Step 1 : Start
Step 2 : Read number of terms as n
Step 3 : Initialize 0 to f1, 1 to f2 and 2 to i
Step 4 : Print initial fibonacci terms f1, f2
Step 5 : Generate next term using the formula f3 = f1 + f2
Step 6 : Print f3
Step 7 : Increment i by 1
Step 8 : Assign f2 to f1
Step 9 : Assign f3 to f2Step 10 : Repeat steps 59 until i n
Step 11 : Stop
Program (fibo.sh)
# Fi bonacci ser i es usi ng whi l e l oopecho - n "Ent er number of t er ms : "r ead necho "Fi bonacci Ser i es"
f 1=0f 2=1echo - n "$f 1 "echo - n " $f 2 "i =2
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
43/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
whi l e [ $i - l t $n ]do
f 3= expr $f 1 + $f 2`echo - n " $f 3 "f 1=$f 2f 2=$f 3
i = expr $i + 1`doneecho
Output
[ vi j ai @l ocal host l oops] $ sh fibo.shEnt er number of t erms : 8Fi bonacci Ser i es0 1 1 2 3 5 8 13
2.4.EPrime Number
Algorithm
Step 1 : Start
Step 2 : Read the value of nStep 3 : Initialize i to 2
Step 4 : If n is divisible by i thenPrint Not Prime and Stop
Step 5 : Increment iby 1Step 6 : Repeat steps 4 and 5 until i n/2
Step 7 : Print "Prime"
Step 8 : Stop
Program (prime.sh)
# Pr i me number usi ng exi techo - n "Ent er t he number : "r ead ni =2m= expr $n / 2`unt i l [ $i - gt $m]do
q= expr $n % $i `i f [ $q - eq 0 ]t hen
echo " Not a Pr i me number "exi t
f ii = expr $i + 1`
doneecho "Pr i me number "
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
44/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host l oops] $ sh prime.shEnt er t he number : 17Pr i me number
2.4.FFactorial Value
Algorithm
Step 1 : Start
Step 2 : Readnumber
Step 3 : Initialize 1 to factandnumberto i
Step 4 : fact= fact* i
Step 5 : Decrement i by 1
Step 6: Repeat steps 46 until i > 0Step 7 : Print fact
Step 8 : Stop
Program (fact.sh)
# Fact or i al val ue usi ng unt i lecho - n "Ent er a posi t i ve number : "r ead nf =1unt i l [ $n - l t 1 ]do
f = expr $f \ * $n`n= expr $n - 1`
doneecho "Factor i al val ue : $f "
Output
[ vi j ai @l ocal host l oops] $ sh fact.shEnt er a posi t i ve number : 10Fact or i al val ue : 3628800
2.4.GSum of 1..N natural numbers
Algorithm
Step 1 : StartStep 2 : Readn
Step 3 : Initialize 0 to sum and 1 to i
Step 4 : Addi to sum
Step 5 : Increment i by 1
Step 6: Repeat steps 46 until i n
Step 7 : Print sum
Step 8 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
45/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (sum1ton.sh)
# Sum of 1+2+3+ . . . +N number secho - n "Ent er N val ue : "r ead nsum=0i =1
unt i l [ $i - gt $n ]do
sum= expr $sum + $i `i = expr $i + 1`
doneecho "The sum of n number s i s $sum"
Output
[ vi j ai @l ocal host l oops] $ sh sum1ton.shEnt er N val ue : 26
The sum of n numbers i s 351
2.4.HData Statistics
Algorithm
Step 1 : Start
Step 2 : Initialize 0 to pc, sum, i
Step 3 : Read a number
Step 4 : Ifnumber= 9999 then goto step 10
Step 5 : Increment i by 1
Step 6 : Ifnumber 0 then goto step 3
Step 7 : Increment pc by 1
Step 8 : Addnumberto sum
Step 9 : Goto step 3
Step 10 : Compute avg = sum / pcStep 11 : Print i, pc, avg,
Step 12 : Stop
Program (datastat.sh)
# Aggr egate of posi t i ve nos usi ng br eak and cont i nuecl earpc=0
s=0i =0
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
46/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
unt i l f al sedo
echo - n "Ent er a number ( 9999 t o qui t ) : "r ead ni f [ $n - eq 9999 ]t hen
br eakf ii = expr $i + 1`i f [ $n - l e 0 ]t hen
cont i nuef ipc= expr $pc + 1`s= expr $s + $n`
doneavg= expr " scal e=2; $s / $pc" | bc`echo "Tot al No. of ent r i es : $i "
echo "No. of posi t i ve dat as : $pc"echo "Posi t i ve aggr egate : $avg"
Output
[ vi j ai @l ocal host l oops] $ sh datastat.shEnt er a number ( 9999 t o qui t ) : 32Ent er a number ( 9999 t o qui t ) : 78Ent er a number ( 9999 t o qui t ) : 0Ent er a number ( 9999 t o qui t ) : 11Ent er a number ( 9999 t o qui t ) : 47Ent er a number ( 9999 t o qui t ) : - 9Ent er a number ( 9999 t o qui t ) : 12Ent er a number ( 9999 t o qui t ) : 7Ent er a number ( 9999 t o qui t ) : 9999
Tot al No. of ent r i es : 8No. of posi t i ve dat as : 6Posi t i ve aggr egat e : 31. 16
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
47/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 2.5 SHELL SCRIPTS
Aim
To write shell scripts using shell commands.
The shell's programming features coupled with the UNIX commands make it an extremely
useful programming language. It is programming practice to tell the system that the file
contents are set of commands to be interpreted by the specified shell in the first line as
#! / bi n/ bash
File Test operations
The following are some of the options for test expressions that work with files.
Condition Return value
- efilename true if file exists- f filename true if file exists and is ordinary
- dfilename true if file exists and is directory- r filename true if file exists and is readable- wfilename true if file exists and is writeable- x filename true if file exists and is executable- s filename true if file exists and is non-empty
file1 - nt file2 true if file1 is newer than file2
Special Variables
Shell posses certain special variables prefixed by a $ reserved for specific functions. These
are also known as positional parameters. Some of them are
Variable Description$0 Name of the script$n Command-line arguments ($1 for first, $2 for second argument, and so on)$# Number of arguments supplied to the script$? Exit status of the recent command
ResultThus programming constructs using shell commands were executed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
48/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.ATime based greeting
Program (wish.sh)
#! / bi n/ bashx= dat e +%Hmr d= dat e +%P`i f [ $mr d==' am' ]t hen
i f [ $x - l e 11 ]t hen
echo "Good Mor ni ng"f i
el sei f [ $x - l e 2 ]t hen
echo "Good Af t ernoon"el i f [ $x - l e 6 ]t hen
echo "Good Eveni ng"el se
echo "Good Ni ght "f i
f i
Output[ vi j ai @l ocal host command] $ sh wish.shGood Mor ni ng
2.5.BNumber of days in a month
Program (monthdays.sh)
# Number of days i n a mont hmt h= dat e +%mmn= dat e +%B`case $mt h i n
02) echo "Febr uar y usual l y has 28 days"echo "I f l eap year , t hen i t has 29 days" ; ;
04| 06| 09| 11) echo "The cur r ent mont h $mn has 30 days" ; ;*) echo "The cur r ent month $mn has 31 days"
esac
Output
[ vi j ai @l ocal host command] $ sh monthdays.shThe cur r ent month Apr i l has 30 days
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
49/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.CCommands menu
Program (cmdmenu.sh)
# Menu pr ogr amch=' y'whi l e [ $ch == ' y' ]do
echo - e " \ t MENU1. Li st of f i l es2. Wor ki ng Di r ect or y3. Dat e and Ti me4. User s of t he system5. Cal endarEnt er t he opt i on : \ c"
r ead choi cecase "$choi ce" i n
1) l s - l ; ;2) pwd ; ;3) dat e ; ;4) who ; ;5) cal
esacecho - n "Do you wi sh t o cont i nue ( y/ n) : "r ead ch
done
Output
[ vi j ai @l ocal host command] $ sh cmdmenu.shMENU
1. Li st of f i l es2. Wor ki ng Di r ect or y3. Dat e and Ti me4. User s of t he system5. Cal endarEnt er t he opt i on : 4
vi j ai pt s/ 20 Apr 4 13: 41 ( l i nux- 21. smkf omr a. com)cse1 pt s/ 13 Apr 4 13: 43 ( scl - 58. smkf omr a. com)Do you wi sh t o cont i nue (y/ n) : n
2.5.DDirectory Listing
Program (cmdmenu.sh)
f or x i n .do
l s - R $xdone
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
50/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host command] $ sh list.sh. :l i s t . sh shel l scr i pts
. / shel l scr i pt s:
command deci si on l oops pat mat ch si mpl e
. / shel l scr i pt s/ command:cmdmenu. sh debug. sh dupr emove. sh f i l etype. sh keyst r oke. sh
. / shel l scr i pt s /deci si on:bi g3. sh emppay. sh gr ade. sh l eap. sh oddeven. sh st r comp. sh
. / shel l scr i pt s / l oops:ar mst r ong. sh dat ast at . sh f act . sh f i bo. sh mul t abl e. sh
. / shel l scr i pt s/ pat mat ch:cal c. sh r ent al . sh vot e. sh vowel . sh
. / shel l scr i pt s/ s i mpl e:ci r cl e. sh degconv. sh si mpi nt . sh swap. sh
2.5.EDetecting file type
Program (filetype.sh)
# Fi l e t ypeecho - n "Ent er f i l ename : "r ead f name
i f [ - e $f name ]t heni f [ - f $f name ]t hen
echo "Regul ar f i l e"el i f [ - d $f name ]t hen
echo "Di r ect or y"el se
echo "Speci al f i l e"f i
el se
echo "Fi l e does not exi st "f i
Output
[ vi j ai @l ocal host command] $ sh f i l et ype. shEnt er f i l ename : samp. cRegul ar f i l e
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
51/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.FDetecting user when logged on
Program (logdetect.sh)
#! / bi n/ bash#Detect t he user at l ogonwhi l e t r uedo
i f who| gr ep $1>/ dev/ nul lt hen
echo $1 i s l ogged i nexi t
f idone
Output
[ vi j ai @l ocal host command] $ sh logdetect.sh cse1cse1 i s l ogged i n
2.5.GDuplicate file removal
Program (dupremove.sh)
# Dupl i cate f i l e r emovali f cmp $1 $2t hen
echo "Fi l es $1, $2 ar e i dent i cal "rm$2echo "$2 f i l e del et ed"
el seecho "Fi l es $1, $2 ar e di st i nct "
f i
Output
[ vi j ai @l ocal host command] $ sh dupremove.sh samp.c s.cFi l es samp. c, s. c ar e i dent i cals . c f i l e del et ed
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
52/81
Shell Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
2.5.HCompilation and execution of a C program
Program (debug.sh)# Compi l e and execut ewhi l e t r uedo
gcc - o $1. out $1. ccase "$?" i n0) echo "Execut i ng . . . "
. / $1. outexi t ; ;
*)sl eep 5vi $1. c
esacdone
Output
[ vi j ai @l ocal host command] $ sh debug. sh sampsamp. c: 4: 10: war ni ng: mul t i - l i ne st r i ng l i t er al s ar edepr ecat edsamp. c: 4: 10: mi ssi ng t er mi nat i ng " charact ersamp. c: 4: 10: possi bl e st ar t of unt er mi nat ed st r i ng l i t er alsamp. c: I n f unct i on `mai n' :samp. c: 4: par se er r or at end of i nputExecut i ng . . .Hel l o
2.5.IKeystroke detection
Program (keystroke.sh)# Detect key st r okeecho "Hi t a key and t hen hi t r et ur n. "r ead Keypr esscase "$Keypr ess" i n
[ [ : l ower : ] ] ) echo "Lower case l et t er "; ;[ [ : upper : ] ] ) echo "Upper case l et t er "; ;[ 0- 9] ) echo "Di gi t "; ;* ) echo "Punct uat i on, whi t espace, or ot her "; ;
esac
Output[ vi j ai @l ocal host command] $ sh keyst r oke. sh8Di gi t
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
53/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.1 Introduction to Pointers
AimTo learn the concept of pointers in C programs.
Data for a variable is stored at some memory location. Address andData are two sides an
variable. For instance x = 10 is represented as
Variable Data Address
x 3221216948
The address of a variable can be obtained using & operator known as reference operator. The
variable's value can be obtained using the dereference operator*.
Pointer Variable
A Pointer variable or a pointer is a special variable that holds the address of another variable.Pointer variable are distinguished from other variables by having an asterik (*) prefixed in thedeclaration statement.
i nt x, * i pt r ;
A pointer variable is a derived data type based on either standard, derived or user-defined
data type. A pointer variable can be made to point any variable of its base type by assigning
the variable's address to the pointer. For instance, an integer pointer can point to an integer
variable only. A pointer variable is allocated 2 bytes irrespective of the data type it points.
pt r = &x; / * Assi gni ng addr ess X t o poi nt er */
Value of the variable pointed to can be accessed by applying the dereference operator
pr i nt f ( "Val ue of t he var i abl e poi nt ed t o %d", *pt r ) ;
A pointer of type void is referred to as generic pointer i.e. it can point to any data type. Since
pointer variables hold address, integers could be added or subtracted to yield another address.
A pointer that holds the address of another pointer variable is known as pointer-to-pointer.
ResultThus C programs using pointers were executed.
10
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
54/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.1.AReference and Dereference operator
Algorithm
Step 1 : StartStep 2 : Initialize x to 10
Step 3 : Print the value ofxStep 4 : Print the address ofx using address operator
Step 5 : Print the value ofx by dereferencing the address operatorStep 6 : Stop
Program (refderef.c)
/ * Data and addr ess * /#i ncl ude mai n( ){
i nt x;x=10;
pr i nt f ( "Val ue of x i s %d", x) ;pr i nt f ( "\ nAddr ess of x i s %u" , &x) ;pr i nt f ( "\ nVal ue of x i s %d\ n" , *( &x) ) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc refderef.c[ vi j ai @l ocal host poi nt er ] $ ./a.outVal ue of x i s 10Addr ess of x i s 3221216948Val ue of x i s 10
3.1.BPointer variables
Algorithm
Step 1 : Initialize two integer variables x andy with some values.
Step 2 : Create a pointeriptrof integer type
Step 3 : Assign the address ofx to iptr
Step 4 : Print the value and address stored in iptr
Step 5 : Assign the address ofy to iptr
Step 6 : Print the value and address stored in iptr
Step 7 : Print the storage requirement ofiptr, address ofiptrandmain function
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
55/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptrvar.c)
/ * Poi nt er var i abl es */# i ncl udemai n( ){
i nt x, y, * i pt r ;
x = 125;i pt r = &x ; / * i pt r poi nt s t o x */y = 23;f l oat * f pt r ;
pr i nt f ( "X val ue i s %d and st or ed at %u\ n" , x, &x) ;pr i nt f ( "Y val ue i s %d and st or ed at %u\ n" , y, &y) ;
pr i nt f ( "\ nI nt poi nt er hol ds t he addr ess %u\ n", i pt r ) ;pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *i pt r ) ;
i pt r = &y; / * i pt r poi nt s t o y */pr i nt f ( "\ nI nt poi nt er now hol ds t he addr ess %u\ n" , i pt r ) ;
pr i nt f ( "Accessi ng val ue thr u poi nt er : %d\ n" , *i pt r ) ;
pr i nt f ( "\ nSi ze of i nt poi nt er : %d byt es", s i zeof ( i pt r ) ) ;pr i nt f ( "\ nSi ze of f l oat poi nt er : %d byt es", s i zeof ( f pt r ) ) ;pr i nt f ( "\ n\ nAddr ess of mai n f unct i on i s %u\ n" , mai n) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptrvar.c[ vi j ai @l ocal host poi nt er ] $ ./a.outX val ue i s 125 and st or ed at 3221216452
Y val ue i s 23 and st or ed at 3221216448
I nt poi nter hol ds t he addr ess 3221216452Aceesi ng val ue t hr o poi nt er : 125
I nt poi nter now hol ds t he addr ess 3221216448Accessi ng val ue t hr o poi nt er : 23
Si ze of i nt poi nt er : 4 byt esSi ze of f l oat poi nt er : 4 byt es
Address of mai n f unct i on i s 134513448
3.1.CPointertoPointer
Algorithm
Step 1 : Demonstrate void pointer by making it to point to variables of different type
Step 2 : Declare a pointer variable p1 and assign a variable's address of its type
Step 3 : Declare a double pointerp2 and assign it the address ofp1
Step 4 : Display the address stored in p1, data accessed using p1 andp1's address
Step 5 : Display the address stored in p2, data accessed using p2 andp2's address
Step 6 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
56/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptrtoptr.c)
/ * Poi nt er var i abl es */# i ncl udemai n( ){
i nt x=12, *p1, **p2;
f l oat z=8. 5;voi d *pt r ; / * Gener i c poi nt er */pt r = &x ; / * pt r poi nt s t o x ( i nt ) */pt r = &z; / * pt r poi nt s t o y ( f l oat ) */
p1 = &x;p2 = &p1; / * Poi nt er t o poi nter * /pr i nt f ( "X val ue i s %d and st or ed at %u\ n" , x, &x) ;
pr i nt f ( "\ nPoi nt er hol ds t he addr ess %u\ n", p1) ;pr i nt f ( "Aceesi ng val ue t hr u poi nt er : %d\ n", *p1) ;pr i nt f ( "Poi nt er i s st or ed at l ocat i on : %u\ n", &p1) ;
pr i nt f ( "\ nPoi nt er - t o- poi nt er hol ds t he addr ess %u\ n", p2) ;pr i nt f ( "Accessi ng val ue thr u pt r - t o- pt r : %d\ n", **p2) ;
pr i nt f ( "\ nSi ze of pt r - t o- pt r: %d byt es\ n", s i zeof ( pt r ) ) ;}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptrtoptr.c[ vi j ai @l ocal host poi nt er ] $ ./a.outX val ue i s 12 and st ored at 3221220804
Poi nt er hol ds t he addr ess 3221220804
Aceesi ng val ue t hr u poi nt er : 12Poi nt er i s st or ed at l ocat i on : 3221220800
Poi nt er - t o- poi nt er hol ds the addr ess 3221220800Accessi ng val ue t hr u pt r - t o- pt r : 12
Si ze of pt r - t o- pt r : 4 byt es
3.1.DAddition using pointers
Algorithm
Step 1 : Start
Step 2 : Read the values ofa andb
Step 3 : Assign the address ofa andb to x andy
Step 4 : Sum the values at locations pointed by x and y and store in c
Step 5 : Print c
Step 6 : Stop
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
57/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Program (ptradd.c)
/ * Addi t i on oper at i ons usi ng poi nt er s */#i ncl udemai n( ){
i nt a, b, c;
i nt *pa, *pb;pa=&a;pb=&b;pr i nt f ( "Ent er val ues f or A and B : ") ;scanf ( "%d%d" , &a, &b) ;c = *pa + *pb;pr i nt f ( "Sum = %d\ n" , c) ;
}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc ptradd.c
[ vi j ai @l ocal host poi nt er ] $ ./a.outEnt er val ues f or A and B : 4 6Sum = 10
3.1.EBasic Calculator
Algorithm
Step 1 : StartStep 2 : Read the values ofa andb
Step 3 : Assign the address ofa andb to pointers pa andpbStep 4 : Display a simple calculator menu
Step 5 : Based on user choice, perform arithmetic operations using pointer variablesStep 6 : Display the result
Step 7 : Stop
Program (ptrcalc.c)
/ * Ar i t hmet i c oper at i ons usi ng poi nt er s */#i ncl udemai n( ){
i nt a, b, c;i nt *pa, *pb;
char op;pa=&a;pb=&b;
pr i nt f ( "Basi c Cal cul at or ") ;pr i nt f ( "\ n + Addi t i on") ;pr i nt f ( "\ n - Subt r act i on") ;pr i nt f ( " \ n * Mul t i pl i cat i on") ;pr i nt f ( "\ n / Quot i ent ") ;
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
58/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
pr i nt f ( "\ n % Remai nder ") ;pr i nt f ( "\ n x Qui t ") ;pr i nt f ( "\ nEnt er oper at or : ") ;scanf ( "%c" , &op) ;pr i nt f ( "Ent er t wo i nt eger s : ") ;scanf ( "%d%d" , &a, &b) ;
swi t ch ( op){
case ' +' :c = *pa + *pb;break;
case ' - ' :c = *pa - *pb;break;
case ' * ' :c = *pa * *pb;break;
case ' / ' :c = *pa / *pb;break;
case ' %' :c = *pa % *pb;break;
def aul t :exi t (0) ;
}pr i nt f ( " %d %c %d = %d\ n" , a, op, b, c) ;
}
Output[ vi j ai @l ocal host poi nt er ] $ gcc ptrcalc.c[ vi j ai @l ocal host poi nt er ] $ ./a.outBasi c Cal cul at or
+ Addi t i on- Subt r act i on* Mul t i pl i cat i on/ Quot i ent% Remai nderx Qui t
Ent er oper at or : +Ent er t wo i nt eger s : 12 23
12 + 23 = 35
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
59/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Ex. No: 3.2 Pointer Programming
AimTo study the advantages of using pointers in C programming.
Pointers & Function
Arguments passed to functions are pass by value i.e., a copy of value of the actual argumentsare passed. Therefore changes made to formal arguments are not reflected to actual
arguments. However, to have the actual arguments modified during process by anotherfunction, then addresses of the arguments are passed, instead of values through pointers. This
is known as pass by reference. Another use of pointers in function is that an address could be
returned, known as return by reference.
Pointers & Arrays
Pointers can be used for efficient traversal of a given array. An array name by itself is a
pointer to the first element in the array. The address of first element of array X can be
expressed as either &X[0] orX. The i+1
th
element is termed as &X[i] orX+i. The value ofi isreferred to as offset. Thus a pointer can be assigned an array variable and array elements can
be accessed by altering the offset. Similarly for two-dimensional array, Xi+1,j+1 element could
be accessed as * (* (X+ i) + j).
Pointers & Strings
A string variable alternatively can be declared as a character pointer type since string is
represented as an array of characters. The advantage is that length of the string need not beknown in advance. Strings could be processed using character pointer.
Pointers & Structures
A pointer variable can be assigned a structure as any other type. The members of a structure
are accessed using the indirect selection operator (- >). Self-referential structure is a structurewhere one of its members is a pointer to the structure itself. Such structures are used to
implement data structures such as list and trees.
ResultThus C programs using pointers were executed and its efficacy realized.
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
60/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.APass by value & reference
Algorithm
Step 1 : Define function swapval with parameters of type integer that swaps twovariables using a temporary variable.
Step 2 : Define function swaprefwith parameters of type integer pointerthat swaps twovariables using a temporary variable and pointer notation
Step 3 : In main function get values of two variables, say a andbStep 4 : Call function swapval with a andb as arguments (Call by value)
Step 5 : Print the values ofa andb after function call.
Step 6 : Call function swaprefwith address ofa andb as arguments (Call by reference)
Step 7 : Print the values ofa andb after function call.
Step 8 : Stop
Program (passbyref.c)
/ * Pass by val ue and r ef erence */#i ncl ude
mai n( ){
i nt a, b;voi d swapval ( i nt , i nt ) ; / * Pass by r ef er ence */voi d swapref ( i nt * , i nt * ) ; / * Pass by val ue * /
pr i nt f ( "Ent er t he val ues of A and B : ") ;scanf ( "%d%d" , &a, &b) ;
swapval ( a, b) ; / * Cal l by val ue */pr i nt f ( "\ nVal ues af t er Pass by Val ue\ n" ) ;pr i nt f ( "Val ue of A i s %d\ n", a) ;
pr i nt f ( "Val ue of B i s %d\ n", b) ;swapr ef ( &a, &b) ; / * Cal l by r ef er ence */pr i nt f ( "\ nVal ues af t er Pass by Ref er ence\ n") ;pr i nt f ( "Val ue of A i s %d\ n", a) ;pr i nt f ( "Val ue of B i s %d\ n", b) ;
}
voi d swapr ef ( i nt *x, i nt *y){
i nt t ;t = *x;*x = *y;
*y = t ;}voi d swapval ( i nt a, i nt b){
i nt t ;t = a;a = b;b = t ;
}
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
61/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
Output
[ vi j ai @l ocal host poi nt er ] $ gcc passbyref.c[ vi j ai @l ocal host poi nt er ] $ ./a.outEnt er t he val ues of A and B : 12 23
Val ues af t er Pass by Val ue
Val ue of A i s 12Val ue of B i s 23
Val ues af t er Pass by Ref erenceVal ue of A i s 23Val ue of B i s 12
3.2.BReturn by reference
Algorithm
Step 1 : Define function big with parameters of type integer pointer that returns theaddress of the biggest number using pointers (Return by reference)
Step 2 : In main function get values of two variables, say a andbStep 3 : Call function big with address ofa andb as arguments (Call by reference)
Step 4 : Print value stored at the address returned
Program (retbyref.c)
/ *Ret ur n by r ef er ence*/#i ncl ude i nt * bi g( i nt * x, i nt* y){
i f ( *x > *y)
r et ur n x;el se
r et ur n y;}
mai n( ){
i nt a, b;i nt *p;pr i nt f ( "Ent er t wo val ues : ") ;scanf ( "%d%d" , &a, &b) ;p = bi g( &a, &b) ;
pr i nt f ( "Bi ggest i s %d\ n" , *p) ;}
Output
[ vi j ai @l ocal host poi nt er ] $ gcc retbyref.c[ vi j ai @l ocal host poi nt er ] $ ./a.outEnt er t wo val ues : 3 7Bi ggest i s 7
http://cseannauniv.blogspot.in/http://cseannauniv.blogspot.in/ -
7/28/2019 GE2155 full lab manual
62/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.CSum of one-dimensional array
Algorithm
Step 1 : Declare an integer array and an integer pointerp.Step 2 : Get array elements using a for loop
Step 3 : Assign starting address of the array to pStep 4 : Set up a loop
Step 4.1 : Display the elements value and address using *p andpStep 4.2 : Add elements value to sum
Step 4.3 : Increment p by 1
Step 5 : Display sum
Step 6 : Stop
Program (array1d.c)
/ * Poi nt er s and one- di mensi onal arr ays */#i ncl ude mai n( )
{i nt i , n, sum=0;i nt x[ 25] , *p;pr i nt f ( "Ent er number of el ement s : ") ;scanf ( "%d" , &n) ;pr i nt f ( "Ent er Ar r ay el ement s : ") ;f or ( i =0; i
-
7/28/2019 GE2155 full lab manual
63/81
C Programming GE2155Computer Practice II
http://cseannauniv.blogspot.in Vijai Anand
3.2.DDisplaying a two-dimensional array
Algorithm
Step 1 : Declare a 2D integer array a with 3 rows and 3 columns and initialize it.Step 2 : Set up a loop with index i that iterates for rows.
Step 3 : Set up a loop for the column inde