67
MASTER OF COMPUTER APPLICATIONS I SEMESTER 2013 SCHEME 13MCA17 –UNIX PROGRAMMING LABORATORY MANUAL COMPILED BY

13MCA17- Unix Laboratory Manual 2013

Embed Size (px)

DESCRIPTION

c assignment

Citation preview

Page 1: 13MCA17- Unix Laboratory Manual 2013

MASTER OF COMPUTER APPLICATIONS

I SEMESTER

2013 SCHEME13MCA17 –UNIX PROGRAMMING

LABORATORY MANUAL

COMPILED BY

1. Mr. B.H.Chandrashekar2. Mrs. Ashwini B Madhus

2013-14

Page 2: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

UNIX Programming Laboratory

Subject Code: 13MCA17 I.A. Marks: 50Hours/Week: 3 Exam Marks: 50Total Hours: 42 Exam Hours: 3

A. Explore the Unix environment

B. Explore vi editor with vim tutor. Perform the following operations using vi editor, but not limited to: 1. insert character, delete character, replace character2. Save the file and continue working3. save the file a exit the editor4. quit the editor5. quit without saving the file6. rename a file7. insert lines, delete lines,8. set line numbers9. search for a pattern10. move forward and backward

1. a. Write a shell script that takes a valid directory name as an argument and recursively descend all the subdirectories, finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output.

b. Write a shell script that accepts a path name and creates all the components in that path name as directories. For example, if the script is named mpc, then the command mpc a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.

2. a. Write a shell script that accepts two file names as arguments, checks if the permissions for these files are identical and if the permissions are identical, output common permissions and otherwise output each file name followed by its permissions.

b. Write a shell script which accepts valid log-in names as arguments and prints their corresponding home directories, if no arguments are specified, print a suitable error message.

3. a. Create a script file called file-properties that reads a file name entered and outputs it properties.

b. Write shell script to implement terminal locking (similar to the lock command). It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if match occurs, it must lock the keyword until a matching password is entered again by the user, Note that the script must be written to disregard BREAK, control-D. No time limit need be implemented for the lock duration

Dept.of MCA, RVCE 2

Page 3: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

4. a. Write a shell script that accept one or more filenames as argument and convert all of them to up-percase, provided they exist in current directory. b. Write a shell script that displays all the links to a file specified as the first argument to the script. The second argument, which is optional, can be used to specify in which the search is to be -gin. If this second argument is not present, the search is to begin in current working directory. In either case, the starting directory as well as all its subdirectories at all levels must be searched. The script need not include any error checking.

5. a. Write a shell script that accepts filenames as arguments and displays its creation time if the file ex-ists and if the file does not exists, send output error message.

b. Write a shell script to display the calendar for current month with current date replaced by * or ** depending on whether the date has one digit or two digits.

6. a. Write a shell script to find a file/s that matches a pattern given as command line argument in the home directory, display the contents of the file and copy the file into the directory ~/mydir.

b. Write a shell script to list all the files in a directory whose filename is at least 10 characters. (Use expr command to check the length).

7. a. Write a shell script that gets executed and displays the message either “Good Morning” or “Good Afternoon” or “Good Evening” depending upon time at which the user logs in.

b. Write a shell script that accept a list of filenames as its argument, count and report occurrence of each word that is present in the first argument file on other argument files.

8. a. Write a shell script that determine the period for which a specified user is working on system and display appropriate message.

b. Write a shell script that reports the logging in of a specified user within one minute after he/she log in. The script automatically terminate if specified user does not log in during a specified period of time.

9. a. Write a shell script that accepts the file name, starting and ending line number as an argument and display all the lines between the given line number.

b. Write a shell script that folds long lines into 40 columns. Thus any line that exceeds 40 characters must be broken after 40th, a “\” is to be appended as the indication of folding and the processing is to be continued with the residue. The input is to be supplied through a text file created by the user.

Dept.of MCA, RVCE 3

Page 4: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

10. a. Write an awk script that accepts date argument in the form of mm-dd-yy and displays it in the form of day, month, and year. The script should check the validity of the argument and in the case of er-ror, display a suitable message.

b. Write an awk script to delete duplicated line from a text file. The order of the original lines must remain unchanged.

11. a. Write an awk script to find out total number of books sold in each discipline as well as total book sold using associate array down table as given below.

Electrical 34Mechanical 67Electrical 80Computer Science 43Mechanical 65Civil 98Computer Science 64

b. Write an awk script to compute gross salary of an employee according to rule given below.

If basic salary is < 10000 then HRA=15% of basic & DA=45% of basic.If basic salary is >=10000 then HRA=20% of basic & DA=50% of basic.

Note: In the examination each student picks one question from a lot of all the 11 questions.Question A & B not to be included for examination.

Dept.of MCA, RVCE 4

Page 5: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

CONTENTS

SL. No. Experiments

Page No.

A. Explore the Unix environment

B. Explore vi editor with vim tutor. Perform the following operations using vi editor, but not limited to:

1. insert character, delete character, replace character2. Save the file and continue working3. save the file a exit the editor4. quit the editor5. quit without saving the file6. rename a file7. insert lines, delete lines,8. set line numbers9. search for a pattern10. move forward and backward

11

12

1. a

b

Write a shell script that takes a valid directory name as an argument and recursively descend all the subdirectories, finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output.

Write a shell script that accepts a path name and creates all the components in that path name as directories. For example, if the script is named mpc, then the command mpc a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.

14

15

2. a

B

Write a shell script that accepts two file names as arguments, checks if the permissions for these files are identical and if the permissions are identical, output common permissions and otherwise output each file name followed by its permissions.

Write a shell script which accepts valid log-in names as arguments and prints their corresponding home directories, if no arguments are specified, print a suitable error message.

16

17

3. a

b

Create a script file called file-properties that reads a file name entered and outputs it properties.

Write shell script to implement terminal locking (similar to the lock command). It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if match occurs, it must lock the keyword until a matching password is entered again by the user, Note that the script must be written to disregard BREAK, control-D. No time limit need be implemented for the lock duration

19

20

4. a Write a shell script that accept one or more filenames as argument and convert all of 21

Dept.of MCA, RVCE 5

Page 6: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

b

them to uppercase, provided they exist in current directory.

Write a shell script that displays all the links to a file specified as the first argument to the script. The second argument, which is optional, can be used to specify in which the search is to begin. If this second argument is not present, the search is to begin in current working directory. In either case, the starting directory as well as all its subdi-rectories at all levels must be searched. The script need not include any error check-ing.

22

5. a

b

Write a shell script that accepts filenames as arguments and displays its creation time if the file exists and if the file does not exists, send output error message.

Write a shell script to display the calendar for current month with current date replaced by * or ** depending on whether the date has one digit or two digits.

23

24

6. a

b

Write a shell script to find a file/s that matches a pattern given as command line argu-ment in the home directory, display the contents of the file and copy the file into the directory ~/mydir.

Write a shell script to list all the files in a directory whose filename is at least 10 char-acters. (Use expr command to check the length).

25

26

7. a

b

Write a shell script that gets executed and displays the message either “Good Morn-ing” or “Good Afternoon” or “Good Evening” depending upon time at which the user logs in.

Write a shell script that accept a list of filenames as its argument, count and report oc-currence of each word that is present in the first argument file on other argument files.

27

28

8. a

b

Write a shell script that determine the period for which a specified user is working on system and display appropriate message.

Write a shell script that reports the logging in of a specified user within one minute af-ter he/she log in. The script automatically terminate if specified user does not log in during a specified period of time.

29

30

9. a

b

Write a shell script that accepts the file name, starting and ending line number as an argument and display all the lines between the given line number.

Write a shell script that folds long lines into 40 columns. Thus any line that exceeds 40 characters must be broken after 40th, a “\” is to be appended as the indication of folding and the processing is to be continued with the residue. The input is to be sup-plied through a text file created by the user.

31

32

10. a

b

Write an awk script that accepts date argument in the form of mm-dd-yy and displays it in the form of day, month, and year. The script should check the validity of the ar-gument and in the case of error, display a suitable message.Write an awk script to delete duplicated line from a text file. The order of the original lines must remain unchanged.

34

34

Dept.of MCA, RVCE 6

Page 7: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

11. a

b

Write an awk script to find out total number of books sold in each discipline as well as total book sold using associate array down table as given below.

Electrical 34Mechanical 67Electrical 80Computer Science 43Mechanical 65Civil 98Computer Science 64

Write an awk script to compute gross salary of an employee according to rule given below. If basic salary is < 10000 then HRA=15% of basic & DA=45% of basic. If basic salary is >=10000 then HRA=20% of basic & DA=50% of basic.

35

36

13 Additional Exercises 38 14 Viva Voce questions 39 15 Lab cycles 41

Dept.of MCA, RVCE 7

Page 8: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Do ’ s and Don ’ t in the Laboratory

DO …..Come prepared to the Lab.Submit your Records to the Lecturer and sign in the Log Book on entering the Lab.Follow the Lab exercise cycles as instructed by the Department. Violating the same will result in deduction of marks.Use the same login(if any) assigned to you.Put the chairs back to its position before you leave.Backlog exercises to be executed after completing regular exercises.

DON’T …..Move around in the lab during the lab session.Tamper System Files or Try to access the Server.Write Data Sheets or Records in the Lab.Change the system assigned to you without the notice of the Lab Staff.Teaching your friends.

Dept.of MCA, RVCE 8

Page 9: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Introduction to UNIXFeatures of UNIX

- Multiuser system- Multi-tasking system- The UNIX toolkit- Pattern matching- Programming facility- documentation

Unix Command structureA UNIX command is an action request given to the UNIX shell for execution. All UNIX commands apply an action or a series of actions to some input data and create some output data, and are case sensitive.

The command format is$ verb [options] [arguments]

where verb is the command nameoptions modify how the action is applied and arguments provide additional information to the command

There are a few commands (like pwd ) that don’t take any arguments, some commands (like who, ls ) that may or may not take any arguments and some commands (like cut ) that compulsorily take arguments.

Commands to Execute UNIX Programs

Editor : Vim or Vi

To open a file : vim filename.sh or vi filename.sh

To Execute Shell Script : sh filename.sh

To Execute an AWK Script : awk –f filename.awk

Dept.of MCA, RVCE 9

Page 10: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

SOLUTIONS

Dept.of MCA, RVCE 10

Page 11: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

A. Explore the Unix environment

The traditional Unix environment is a CLI (command line interface), where the user can type commands to tell the computer what to do. Under Ubuntu there are GUIs (graphical user interfaces), where a user can point and click and drag.

A Terminal is very useful tool in UNIX. To open Terminal, press Ctrl+Alt+T on your keyboard. Alternatively a terminal can be opened from Applications > Accessories > Terminal, which is located in main menu.

Once a terminal is opened, use the login credentials given by the system administrator and login. Once successfully logged in, a command prompt appears on the terminal. Try out the following commands and take a tour to familiarize UNIX environment.

pwd: The pwd command will allow you to know in which directory you're located (pwd stands for "print working directory").

ls: The ls command will show you ('list') the files in your current directory. Used with certain options, you can see sizes of files, when files were made, and permissions of files.

cd: The cd command will allow you to change directories. When you open a terminal you will be in your home directory. To move around the file system you will use cd. Examples:

To navigate into the root directory, use "cd /" To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -"

cat: concatenates files. cat > filename will create a file and whatever is typed later is treated as contents of the file. Use ctrl-d to exit the file. cat filename will display the contents of the file.

cp: The cp command will make a copy of a file. Example: "cp file foo" will make an exact copy of "file" and name it "foo", but the file "file" will still be there.

mv: The mv command will move a file to a different location or will rename a file. Examples are as follows: "mv file foo" will rename the file "file" to "foo". The file “file”will no longer be available.

rm: Use this command to remove or delete a file in your directory.

rmdir: The rmdir command will delete an empty directory. To delete a directory and all of its contents recursively,

Dept.of MCA, RVCE 11

Page 12: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

mkdir: The mkdir command will allow you to create directories. Example: "mkdir music" will create a directory called "music".

man: The man command is used to show you the manual of other commands. Try "man man" to get the man page for man itself.

who – displays who all are the logged in users. Try the variants whoami and who am i

date --- shows the current date and time

cal --- shows a calendar of the current month. Use e.g., cal 10 2013 to get the calendar for October 2013, or cal 2013 to get the whole year.

B. Explore vi editor with vim tutor. Perform the following operations using vi editor, but not lim-ited to: 1. insert character, delete character, replace character2. Save the file and continue working3. save the file and exit the editor4. quit the editor5. quit without saving the file6. rename a file7. insert lines, delete lines,8. set line numbers9. search for a pattern10. move forward and backward

UNIX provides vi editor for BSD system – created by Bill Joy. Bram Moolenaar improved the vi editor and called it as vim (vi improved) on Linux OS.

There are 3 modes in vi editor

Command mode : copy and delete text, can’t enter or replace text

Input mode :every key pressed is a text

ex mode : save and perform substitution by pressing : and get back to default command mode

It is possible to display the mode in which is user is in by typing,

:set showmode

Messages like INSERT MODE, REPLACE MODE, CHANGE MODE, etc will appear in the last line.

Insert mode commands FUNCTION

i inserts text

Dept.of MCA, RVCE 12

Page 13: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

a appends text

I inserts at beginning of line

A appends text at end of line

o opens line below

O opens line above

r replaces a single character

s replaces with a text

S replaces entire line d deletex deletes a single characterdd delete entire lineyy copy entire line6dd deletes the current line and five lines below

Ex-mode commands: Saving text and quitting

:W saves file and remains in editing mode

:x saves and quits editing mode

:wq saves and quits editing mode

:w <filename> save as

:w! <filename> save as, but overwrites existing file

:q quits editing mode

:q! quits editing mode by rejecting changes made

:sh escapes to UNIX shell

:recover recovers file from a crash

Navigation

A command mode command doesn’t show up on screen but simply performs a function. To move the cursor in four directions,

k moves cursor upj moves cursor downh moves cursor leftl moves cursor right

Searching for a Pattern

/ search forward? search backward

Dept.of MCA, RVCE 13

Page 14: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Scrollingctrl-f scrolls forwardctrl-b scrolls backwardctrl-d scrolls half page forwardctrl-u scrolls half page backward

Substitution – search and replace:address/source_pattern/target_pattern/flags

Examples:

:1,$s/director/member/g can also use % instead of 1,$:1,50s/unsigned//g deletes unsigned everywhere in lines 1 to 50:3,10s/director/member/g substitute lines 3 through 10:.s/director/member/g only the current line:$s/director/member/g only the last line

Line numbers:set number show line numbers

------------------------------------------------------------------------------------------------------------------------

1a) Write a shell script that takes a valid directory name as an argument and recursively descend all the subdirectories, finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output

clear if [ $# -ne 1 ] then

echo “Invalid Number of arguments passed” exit

fi cd $1

echo The directory name is $1 set -- ` ls -lR| grep -v "^d" |sort -k 5 -rn` echo "size of the largest file $9 is $5 blocks"

Run:sh 1a.sh unix_lab_progsThe directory name is unix_lab_progssize of the largest file example1.sh is 266 blocks

Description $* stands for list of all the command line arguments, (similar to argv[ ] in C) $# for the number of arguments passed along while running the program ( similar to argc in C)

Dept.of MCA, RVCE 14

Page 15: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Sort : sorts the lines of the specified files, typically in alphabetical order. Its syntax is:

% sort [<options>] [<field-specifier>] [<filename(s)>]

cd (change [current working] directory)

 cd <path> : changes your current working directory to path (which can be an absolute or a relative path). One of the most common relative paths to use is '..' i.e. the parent directory of the current directory.

cd resets your current working directory to users home directory (useful if you are lost and want to reach home directory ).

1b) Write a shell script that accepts a path name and creates all the components in that path name as directories. For example, if the script is named mpc, then the command mpc a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.

temp=$IFSIFS=/for i in $* do if [ -d $i ] ; then cd $i else mkdir $i cd $i fidoneIFS=$tempd=`pwd`echo “The current directory structure created is $d”

Run:sh 1b.sh a/b/c/dThe current directory structure created is /home/abm/unix_lab_progs/a/b/c/d

Description mkdir (make directory) mkdir directory creates a subdirectory called  directory in the current working

directory. You can only create subdirectories in a directory if you have write permission on that directory.

pwd : Displays current working directory

IFS or internal field separator is a variable.  The shell uses the value stored in IFS, which is the space, tab, and newline characters by default, to delimit words for the read and set commands, when parsing

Dept.of MCA, RVCE 15

Page 16: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

output from command substitution, and when performing variable substitution. IFS can be redefined to parse one or more lines of data whose fields are not delimited by the default white-space characters

------------------------------------------------------------------------------------------------------------------------------

2a) Write a shell script that accepts two file names as arguments, checks if the permissions for these files are identical and if the permissions are identical, output common permissions and otherwise output each file name followed by its permissions.

if [ $# -eq 0 ] ; then echo “No arguments entered” exitelif [ $# -lt 2 ] ; then echo “Enter 2 filenames to compare” exitelse f1=`ls -l $1|cut -c 2-10` f2=`ls -l $2|cut -c 2-10` if [ "$f1" == "$f2" ] ; then echo “File permission are identical” echo $f1else

echo “File permission are not identical”echo “The permission of first file $1 is : $f1″echo “The permission of the second file $2 is : $f2″

fifi

Run :sh 2a.sh 1a.sh 1b.shpermissions are identicalrw-r--r—

sh 2a.sh 1a.sh sample.shFile permission are not identicalThe permission of first file 1a.sh is : rw-rw-r–The permission of the second file sample.sh is : rwxrw-r–

Description

if-then-else The syntax of the if-then-else construct is

if [ expression ] then

Dept.of MCA, RVCE 16

Page 17: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

simple-command fi or if [ expression ] then

commandlist-1 else commandlist-2 fi

The expression will be evaluated and according to its value, the commandlist-1 or the commandlist-2 will be executed.

ls command with option –l displays all file attributes.

cut command with –c option extracts character, range of characters mentioned in the argument as position of characters to cut command.

2b) Write a shell script which accepts valid log-in names as arguments and prints their correspond-ing home directories, if no arguments are specified, print a suitable error message.

if [ $# -eq 0 ] ; then echo “No arguments” exitfifor nam in $*do y=`grep "$nam" /etc/passwd | cut -d ":" -f1` if [ -n “$y” ] then if [ "$y" = "$nam" ] then x=` grep "$nam" /etc/passwd | cut -d ":" -f6` echo "home directory of $nam is $x" else echo "$nam doesn't have an account " fifi

done

Run: sh 2b.sh mca131home directory of mca101 is /home/mca101

Dept.of MCA, RVCE 17

Page 18: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

sh 2b.sh project1project1 does not have an account

Description : grep : This command is used to search, select and print specified records or lines from an input file grep [ options ] pattern [ filename1 ] [ filename2]…

for loops : used to loop through a list of files, executing some commands on each file. Syntax is

for variable in list do     statements  (referring to $variable) done

The /etc/passwd contains one entry per line for each user (or user account) of the system. All fields are separated by a colon (:) symbol. Generally, passwd file entry looks as follows where the sixth field shows the users home directory.

1. The first field is the user name, i.e. the string a user would type in when logging into the operating system: the logname. Each record in the file must have a unique user name field.

2. The second field stores information used to validate a user's password; however in most modern uses this field is usually set to "x" (or some other indicator) with the actual password information being stored in a separate shadow password file. Setting this field to an asterisk "*" is the typical way to deactivate an account to prevent it being used.

3. The third field is the user identifier, the number that the operating system uses for internal purposes. It does not have to be unique.

4. The fourth field is the group identifier. This number identifies the primary group of the user; all files that are created by this user may initially be accessible to this group.

5. The fifth field, called the Gecos field, is commentary that describes the person or account. Typically, this is a set of comma-separated values including the user's full name and contact details.

6. The sixth field is the path to the user's home directory.

7. The seventh field is the program that is started every time the user logs into the system. For an interactive user, this is usually one of the system's command line interpreters or shell

Dept.of MCA, RVCE 18

Page 19: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

3a. Create a script file called file-properties that reads a file name entered and outputs it properties.

echo “Enter a filename” read file

if [ -f $file ] then set -- `ls -l $file` echo name of file $9 echo file permission $1 echo number of link $2 echo user name $3 echo owner name $4 echo block size $5 echo date of modification $6 echo time of modification $7

else echo The file $file does not exist fi

Run:enter a filename 1a.shname of file 1a.shfile permission -rw-r--r--number of links 1user name abmowner name abmblock size 589date of modification 2013-06-20time of modification 09:34

enter a filenamecheckfileThe file checkfile does not exist

Description

if [ -f $file ] -f option is used check whether the file exists in the current directory or not.

set -- `ls -l $file` : This syntax set the file attributes as positional parameters.[--] specifies not change any of the flags; useful in setting $1 to -.

$1 to $8 are positional parameters.

Dept.of MCA, RVCE 19

Page 20: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

3b.Write shell script to implement terminal locking (similar to the lock command). It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if match occurs, it must lock the keyword until a matching password is entered again by the user, Note that the script must be written to disregard BREAK, control-D. No time limit need be implemented for the lock duration.

clearstty -echoecho "Enter password to lock the terminal"read pass1echo " Re-enter the password"read pass2if [ "$pass1" = "$pass2" ]then echo "Terminal is locked" echo "Enter password to unlock" trap “ ”1 2 3 9 15 18 while true do

read pass3 if [ “$pass1” = “$pass3” ] then echo "Terminal unlocked" stty echo exit else echo "Password Mismatch..Try Again" fi done else echo "Password Mismatch" stty echofi

Run:

Enter password to lock the terminal:****Re-enter the password:****Terminal is lockedEnter the password to unlock:****Terminal unlocked

Enter password to lock the terminal:********Re-enter the password:****Password Mismatch

Dept.of MCA, RVCE 20

Page 21: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Dept.of MCA, RVCE 21

Page 22: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

DescriptionStty –changes the setting of terminals as specified as argument to itStty –echo makes the characters typed invisible on the screenThe trap command provides the script to captures an interrupt (signal) and then clean it up within the

script. The syntax is as follows trap arg signal trap 'action' signal1 signal2 signalNEx: trap 'action' SIGINT trap 'action' SIGTERM SIGINT SIGFPE SIGSTP trap 'action' 15 2 8 20

------------------------------------------------------------------------------------------------------------------------------4a. Write a shell script that accept one or more filenames as argument and convert all of them to uppercase, provided they exist in current directory.

clear if [ $# -eq 0 ] then echo “Error: Insufficient arguments…”

exit fi

for i in $* do if [ -f $i ] then echo it is a valid file echo Contents of file before converting cat $i echo Contents of file after converting tr '[a-z]' '[A-Z]' < $i | tee $i k=`ls $i | tr '[a-z]' '[A-Z]'` mv $i $k echo file $i renamed as $k echo “ directory listing” ls else echo file does not exist fi done

RUN:sh 4a.sh Error: Insufficient arguments…

Sh 4a.sh dirnameIt is a valid file

Dept.of MCA, RVCE 22

Page 23: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Contents of file before convertingThis is lab programContents of file after convertingTHIS IS LAB PROGRAMdirname is renamed as DIRNAMEDirectory listingDIRNAME 1a.sh

Description

tr command : The tr filter manipulates individual characters in a line. It translates characters using one or two compact expressions

tr options expression1expression2 standard input

This command translates each character in expression1 to its counterpart in expression2.

mv command : The mv command is used to move or rename files and directories. This command takes a minimum of 2 arguments

4b. Write a shell script that displays all the links to a file specified as the first argument to the script. The second argument, which is optional, can be used to specify in which the search is to be-gin. If this second argument is not present, the search is to begin in current working directory. In ei-ther case, the starting directory as well as all its subdirectories at all levels must be searched. The script need not include any error checking.

if [ $# -eq 1 ] then tm=`pwd` echo "Directory not given. Using PWD: $tm" else tm=$2 echo "searching from the given directory: $tm" fi t1=`ls -aliR | grep "$1" | cut -d " " -f1 | head -1` echo "the linked files are" ls -liarR $tm | grep "$t1"

Run:sh 4b.sh test sampleSearching from the given directory: sampleThe linked files are179230 -rwxr--r-- 4 abm mca 19 Jul 23 12:35 linked3

Dept.of MCA, RVCE 23

Page 24: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

ln linked3 linked4

sh 4b.sh test sampleSearching from the given directory: sampleThe linked files are179230 -rwxr--r-- 4 abm mca 19 Jul 23 12:35 linked3179230 -rwxr--r-- 4 abm mca 19 Jul 23 12:35 linked4

sh 4b.sh testDirectory not given. Using PWD: /home/abm/unix_lab_progsthe linked files are179230 -rwxr--r-- 3 abm faculty 19 Jul 23 12:35 test179230 -rwxr--r-- 3 abm faculty 19 Jul 23 12:35 linked3179230 -rwxr--r-- 3 abm faculty 19 Jul 23 12:35 linked4

Description

ls command ls lists the contents of a directory.

grep: The Unix grep command helps you search for strings in a file. The grep filter searches the contents of one or more files for a pattern and displays only those lines matching that pattern

ln: ln command creates a hard link to the file. It is same as shortcut to the file.

----------------------------------------------------------------------------------------------------------------------------5a. Write a shell script that accepts filenames as arguments and displays its creation time if the file exists and if the file does not exists, send output error message.

echo Enter the filename to find the creation time:

read filename

if [ -f $filename ]

then

set -- `ls -l $filename`

echo file $filename was created on $6 $7 $8

else

echo file $filename does not exist in the current directory

fi

Run:

sh 5a.sh Enter the filename to find the creation time:

Dept.of MCA, RVCE 24

Page 25: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

testfile test was created on Jul 23 12:35

sh 5a.sh Enter the filename to find the creation time:checkfile check does not exist in the current directory

Description

File tests : file tests are conducted for checking the status of files and directories

if [ -f filename ] This condition returns true value if file exists and is a regular file

if [ -d filename ] This condition returns true value if file exists and is a directory file

5b. Write a shell script to display the calendar for current month with current date replaced by * or ** depending on whether the date has one digit or two digits.

set `date`if [ $3 -le 9 ]then n=`cal | tail -n +3 | grep -n "$3"| cut -d ":" -f1 | head -n 1` n=`expr $n + 2` cal | sed "$n s/$3/*/"else cal | sed "s/$3/**/"fi

Result : :sh 5b.sh July 2013Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 1314 15 16 17 18 19 2021 22 ** 24 25 26 2728 29 30 31

Description

date Shows current date and time.

Dept.of MCA, RVCE 25

Page 26: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

sed: a non-interactive text file editor. It receives text input, whether from stdin or from a file, performs certain operations on specified lines of the input, one line at a time, then outputs the result to stdout or to a file.

Sed determines which lines of its input that it will operate on from the address range passed to it. Specify this address range either by line number or by a pattern to match

6a. Write a shell script to find a file/s that matches a pattern given as command line argument in the home directory, display the contents of the file and copy the file into the directory ~/mydir.

if [ $# -ne 1 ] then echo Insufficient Arguments exitfidir=mydirif [ -d $dir ]then echo "directory $dir already exists.. Not creating again"else mkdir $dirfi echo The files matching the pattern $1 are:ls *$1* > filenames.txtcat filenames.txt

echo The contents of the files arefor i in `cat filenames.txt`do echo "filename: $i" echo “-----------------------------------------“ cat $i echo "---------------------------------------------------------------------------------------------" cp $i ./mydir/$idone

echo "The files copied into ~/mydir"cd mydirls -l

RUN:sh 6a.sh estThe files matching the pattern est are: test

Dept.of MCA, RVCE 26

Page 27: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

test.sh “The contents of the files are”“filename: test”Hello.. welcome to unix

filename: test.shecho “this is sample program for 6a.sh”clear

“The files copied into /home/abm/mydir”total 2-rw-r--r-- 1 mca None 545 Jul 22 11:56 test-rw-r--r-- 1 mca None 168 Jul 22 11:56 test.sh

6b. Write a shell script to list all the files in a directory whose filename is at least 10 characters. (Use expr command to check the length).

clear for i in `ls` do

len=`expr "$i" : '.*'` if [ $len -ge 10 ] then echo $i >> outfile fi done echo “The file names having more than 10 characters are “cat outfile

Run:

touch departments rvcemcadeptsh 6b.shThe file names having more than 10 characters aredepartmentsrvcemcadept

Description expr : This command can be used to perform string manipulations like to find length of string. syntax to find length of string: expr length $stringname

------------------------------------------------------------------------------------------------------------------------------

Dept.of MCA, RVCE 27

Page 28: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

7a. Write a shell script that gets executed and displays the message either “Good Morning” or “Good Afternoon” or “Good Evening” depending upon time at which the user logs in.

hournow=`date | cut –c 12-13`user=`echo $HOME | cut –d ”/” –f 4`case $hournow in[0-1][0-1]|0[2-9]) echo “Good Morning Mr/Ms : $user”;; 1[2-5])echo “Good Afternoon Mr/Ms :$user”;; 1[6-9])echo “Good Evening Mr/Ms :$user”;;esac

Result : :$ sh .bash_profilegood morning abm

Description:case command : This command provides multi way decision making facility.It works on pattern matching.The general format is case string value in pattern1) command command ----------- command ;; pattern 2) command command ----------- command ;; --------- pattern N) command command ----------- command ;; esac When shell comes across a case construct, the behaviour of control flow will be as follows.The string value that appears immediately after the keyword case is compared in turn against each pattern . As soon as a match is found, all the commands following the pattern till the immediate next double semi colon(;;) are executed and then the control goes beyond the esac

Dept.of MCA, RVCE 28

Page 29: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

7b. Write a shell script that accept a list of filenames as its argument, count and report occurrence of each word that is present in the first argument file on other argument files.

if [ $# -lt 2 ]then echo "Error : Insufficient number of arguments" exitfi

str=`cat $1 | tr '\n' ' '`for i in $*do echo "In $i file the count is......" for a in $str do echo "Word = $a, Count = `grep -c "$a" $i`" done echo "----------------------------------------------------------------"done

Run: cat > test1tiger lionelephant

cat > test2tigerTIGERpeacock

cat > test3tiger liontiger fox

sh 7b.sh test1 test2 test3In test1 file the count is......Word = tiger, Count = 1Word = lion, Count = 1Word = elephant, Count = 1----------------------------------------------------------------In test2 file the count is......Word = tiger, Count = 1Word = lion, Count = 0Word = elephant, Count = 0----------------------------------------------------------------In test3 file the count is......Word = tiger, Count = 2

Dept.of MCA, RVCE 29

Page 30: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Word = lion, Count = 1Word = elephant, Count = 0

sh 7b.sh test1Error : Insufficient number of arguments

--------------------------------------------------------------------------------------------------------------------------8a. Write a shell script that determine the period for which a specified user is working on system and display appropriate message.

echo "Enter the Login Name of a User"read usercount=`who | grep -wo "$user" | wc -l`

if [ $count -eq 0 ]then echo "invalid user" exitfi

if [ $count -gt 1 ]then echo "Multiple Login" exitfi

lt=`who |tr -s " " | grep "$user" | cut -d " " -f4`lh=`echo $lt | cut -d ":" -f1` lm=`echo $lt | cut -d ":" -f2` ch=`date +%H` cm=`date +%M`if [ $lh = $ch ]then hr=0 if [ $cm -gt $lm ] then min=`expr $cm - $lm ` else min=`expr $cm - $lm + 60` fi

echo " The user is logged in from $hr hour $min minutes" exitfi

Dept.of MCA, RVCE 30

Page 31: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

if [ $cm -gt $lm ] then min=`expr $cm - $lm ` hr=`expr $ch - $lh` else min=`expr $cm - $lm + 60` hr=`expr $ch -$lh - 1` fi echo " The user is logged in from $hr hour $min minutes"

Run:

Sh 8a.sh Enter the Login Name of a Usermca219The user is logged in from 1 hour 20 minutes

Sh 8a.shEnter the Login Name of a User AbcInvalid user

8b. Write a shell script that reports the logging in of a specified user within one minute after he/she log in. The script automatically terminate if specified user does not log in during a specified period of time.

echo Enter the login name of the user: read usertime=0 who | grep "$user" >/dev/null

if [ $? -eq 0 ] then echo "$user has already logged in.. Give a different user name" exit fi while [ true ]do sleep 1 time=`expr $time + 1`

who | grep "$user" >/dev/null if [ $? -eq 0 ] then echo "$user logged in $time seconds..."

Dept.of MCA, RVCE 31

Page 32: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

exit fi

if [ $time -eq 61 ] then echo "$user did not login within 1 minute" exit fidone

Run: :Enter the login name of the user mca219mca219 logged in 25 seconds

Enter the login name of the user:abmabm has already logged in.. Give a different user name

Enter the login name of the user mca250mca250 did not login within 1 minute

Description

sleep command : Using this command the user can make the system sleep, that is , pause for some fixed period of time.

----------------------------------------------------------------------------------------------------------------------------

9a. Write a shell script that accepts the file name, starting and ending line number as an argument and display all the lines between the given line number. if [ $# -ne 3 ] then echo "Error : Invalid number of arguments." exitfi

if [ $2 -gt $3 ]then

echo "Error : Invalid range value." exit

fil=`expr $3 - $2 + 1`cat $1 | tail –n +$2 | head -$l

Dept.of MCA, RVCE 32

Page 33: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Run:sh 9a.sh test1 5 7

abc 1234 def 5678

ghi 91011 sh 9a.sh test1 15 7 Error : Invalid range value

Description :

head command : This command is used to display at the beginning of one or more files. By default it

displays first 10 lines of a file. syntax is: head [ count option ] filename

tail command : This command is used to display last few lines at the end of a file. . By default it displays last 10 lines of a file

tail [ +/- start ] filename start is starting line number tail -5 filename : It displays last 5 lines of the file

tail +5 filename : It displays all the lines ,beginning from line number 5 to end of the file

9b. Write a shell script that folds long lines into 40 columns. Thus any line that exceeds 40 charac-ters must be broken after 40th, a “\” is to be appended as the indication of folding and the process-ing is to be continued with the residue. The input is to be supplied through a text file created by the user.

echo "Enter the filename"read file

lines=`wc -l < $file`echo "File $file has $lines Lines...."

count=1

if [ -f temp.txt ]then rm temp.txtfi

while [ $count -le $lines ]

Dept.of MCA, RVCE 33

Page 34: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

do lb=1 ub=40 char=0

text=`tail -n +$count $file | head -1` char=`echo $text | wc -c` #echo "There are $char characters in this line" chartemp=$char

if [ $char -le 40 ] then echo $text >> temp.txt else while [ $char -gt 40 ] do

t=`echo "$text" | cut -c $lb-$ub` echo "$t \\" >> temp.txt char=`expr $char - 40`

if [ $char -le 40 ] then echo "$text" | cut -c $ub-$chartemp >> temp.txt fi lb=`expr $lb + 40` ub=`expr $ub + 40` done fi count=`expr $count + 1`done

echo " Contents of the file after folding are: "cat temp.txt

Run:$sh 9b.shEnter the filename

fold_sampleFile fold_sample has 3 Lines.... Contents of the file after folding are:1234567890 1234567890 1234567890 1234567 \7890there is a sample line inside this to ch \heck file folding program----------------------------------------------------------------------------------------------------------------------------

Dept.of MCA, RVCE 34

Page 35: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

10a. Write an awk script that accepts date argument in the form of mm-dd-yy and displays it in the form of day, month, and year. The script should check the validity of the argument and in the case of error, display a suitable message.

BEGIN {system("clear");da="312831303130313130313031"mo="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"mm=substr(ARGV[1],1,2)dd=substr(ARGV[1],4,2)yy=substr(ARGV[1],7,4)if(dd > substr(da,2*mm-1,2) || (mm>12) || ARGC !=2) print "Invalid date"else printf "The day is %d\n The month is %s\n The year is %d\n",dd,substr(mo,3*mm-2,3),yy}

Run: $awk -f 10a.awk 12-07-2013 The day is 7 The month is DEC The year is 2013

DescriptionAwk scripts consist of 3 parts

1. Before (denoted using: BEGIN) - executed prior to the first line of the input being read

2. During (Main Awk loop) - Focuses on looping through lines of input

3. After (denoted using: END) executed after last line of input has been processed

Note : BEGIN and END comments are optional

10b. Write an awk script to delete duplicated line from a text file. The order of the original lines must remain unchanged.

{ a[n++]=$0 } END { for(i=0;i<n;i++) { flag=0; for(j=0;j<i;j++)

Dept.of MCA, RVCE 35

Page 36: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

{ if( a[i] == a[j]) { flag=1; break; } } if (flag == 0) printf “%s \n”, a[i]}}

Run: $ cat test college college bangalore $ awk -f 10b.awk test college Bangalore--------------------------------------------------------------------------------------------------------------------------

11a. Write an awk script to find out total number of books sold in each discipline as well as total book sold using associate array down table as given below.

Electrical 34Mechanical 67Electrical 80Computer Science 43Mechanical 65Civil 98Computer Science 64

BEGIN {print “TOTAL NUMBER OF BOOKS SOLD IN EACH CATEGORY”} { books[$1]+=$2} END {

for (item in books) {

printf (“ %s sold= %d\n”,item,books[item]} total +=books[item]

}

Dept.of MCA, RVCE 36

Page 37: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

printf(”Total books sold=%d”,total) }

Run:

TOTAL NUMBER OF BOOKS SOLD IN EACH CATEGORY

electrical 114 mechanical 137 computers 107 civil 198

Total books sold = 556

DescriptionAssociative arrays are like traditional arrays except they uses strings as their indexes rather than numbers. When using an associative array, you can mimic traditional array by using numeric string as index.

Syntax: arrayname[string]=value

In the above awk syntax:

arrayname is the name of the array, string is the index of an array, value is any value assigning to the el-ement of the array.

To access all the array elements, you can use a loop to go through all the indexes of an array as shown be-low.

Syntax: for (var in arrayname)actions

In the above awk syntax: var is any variable name in is a keyword arrayname is the name of the array. actions are list of statements to be performed. If you want to perform more than one action, it has

to be enclosed within braces.

11b. Write an awk script to compute gross salary of an employee according to rule given below. If basic salary is < 10000 then HRA=15% of basic & DA=45% of basic. If basic salary is >=10000 then HRA=20% of basic & DA=50% of basic

BEGIN {

printf "Enter the Basic Pay : Rs. "

getline bp < "/dev/tty"

Dept.of MCA, RVCE 37

Page 38: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

if(bp<10000)

{ hra=.15*bp

da=.45*bp

}

else

{

hra=.2*bp

da=.5*bp

}

gs=bp+hra+da

printf "Gross Salary = Rs. %.2f\n", gs

}

Run:

$awk –f 11b.awk

Enter the Basic Pay : Rs. 10000

Gross Salary = Rs. 17000

Description

The getline command can be used without arguments to read input from the current input file. All it does

in this case is read the next input record and split it up into fields. This is useful if you've finished

processing the current record, but you want to do some special processing right now on the next record.

getline < file

This form of the getline function takes its input from the file file. Here file is a string-valued expression

that specifies the file name. `< file' is called a redirection since it directs input to come from a differ-

ent place. This form is useful if you want to read your input from a particular file, instead of from the

main input stream.

Dept.of MCA, RVCE 38

Page 39: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Additional Exercises

1. Write a shell script to find the sum of individual digits of a number.

2. Write a shell script to find a given number is even or odd.

3. Write a shell script to create 2 directories and store 10 files in one directory using file related

commands and transfer all files to other directory.

4. Write a shell script to find whether a given number is prime or not

5. Write a shell script to copy a file with all types of validation.

6. Write a shell script to store data in a file and compress it.

7. Write a shell script to display a given number in terms of words using switch statement.

8. Write a shell script to implement wc with all 3 options.

9. Write a shell script to add even numbered and odd numbered positional parameters values

10. Write a shell script to display N Fibonacci sequence.

11. Write an awk script that folds long lines into 40 columns. Thus any line that exceeds 40 characters must be broken after 40th, a ”\” is to be appended as the indication of folding and the processing is to be continued with the reside. The input is to be supplied through a text file created by the user.

12. Write an awk script to accept a file name and find out number of records and field separator in the file.

13.Write a sed instruction to find whether the given file has execute permission for the group the owner belongs to.

   

Dept.of MCA, RVCE 39

Page 40: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Viva - Voce Questions

1.) What is cal command's Result : with and without argument?

2) What will be the output of echo command without any argument?

3) What will ls command with -i option display?

4) What does the following file handling commands perform with its options:

i) cp ii) rm

5) What does cd command do when used without arguments?

6) What is option and argument to the command?

7) List out the types of shells present?

8) What is the need of split command?

9) What are the 3 modes of vi editor?

10) How can we change from one mode to another mode in vi editor?

11) Explain tput command with its arguments?

12) What is the option used with ls command to display file attributes, inode number and hidden files?

13) What is the need of cut command?

14) What is the use of | operator?

15) How do we use cat command to display contents of file, create a file and append to a file?

16) Name the command to create a link for a file and explain the syntax?

17) Explain tee command.

18) Explain substitution command in sed?

19) What are the commands used in ex mode of vi editor?

20) Explain the chmod command

21) Name the command which is used to display the output in terminal as well in the file?

22) How can we change the permission of a file?

23) What does tail command means?

24) What does head command means?

25) What does tr command do?

26) What are the options used with wc command to know number of words , number of lines and number

of characters in a file?

Dept.of MCA, RVCE 40

Page 41: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

27) Explain sort command with any 2 options

28) How can we find out the number of users who have logged on into the system?

29) What is the need of grep command?

30) What is the option used with grep command to display line number where the pattern is found?

31) Explain any 3 options of grep command with suitable example

32) What is the use of -v option in grep command?

33) What is .bash_profile?

34) What is a shell script?

35) Explain 1) $# 2) $*

36) What is sed instruction? Explain the following with respect to sed:

a. Line addressing

b. Context addressing

37) Explain any four built in variables of awk with examples.

38) Explain the control flow feature in awk?

39) When do we use set command?

40) What is a filter? Give some examples of filter command.

41) How can you extract only day from date command?

42) Name any 2 system defined functions in awk?

43) What is the need of using double hypen(--) in this statement: set - - ls –l $filename

44) List out the various system variables used in awk script

45) What does system variable NF and NR denote in awk script

46) Distinguish between whoami and who am i.

47) Name the default shell.

48) Mention the methods available to change file permissions

49) What is the use of IFS?

50) What is the use of script command? What are the options of script command?

Dept.of MCA, RVCE 41

Page 42: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

R V COLLEGE OF ENGINEERING

DEPARTMENT OF MCA

UNIX Programming Laboratory - LABCYCLES

Lab Cycle 1:A. Explore the Unix environment

B. Explore vi editor with vim tutor. Perform the following operations using vi editor, but not limited to: 1. insert character, delete character, replace character 2. Save the file and continue working3. save the file a exit the editor4. quit the editor5. quit without saving the file6. rename a file7. insert lines, delete lines,8. set line numbers9. search for a pattern10. move forward and backward

Lab Cycle 2:1a. Write a shell script that takes a valid directory name as an argument and recursively

descend all the subdirectories, finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output.

b. Write a shell script that accepts a path name and creates all the components in that path name as directories. For example, if the script is named mpc, then the command mpc a/b/c/d should create directories a, a/b, a/b/c, a/b/c/d.

Lab Cycle 3:2a. Write a shell script that accepts two file names as arguments, checks if the permissions for these

files are identical and if the permissions are identical, output common permissions and otherwise output each file name followed by its permissions.

b. Write a shell script which accepts valid log-in names as arguments and prints their corresponding home directories, if no arguments are specified, print a suitable error message.

Lab Cycle 4:

3a. Create a script file called file-properties that reads a file name entered and outputs it properties.

b. Write shell script to implement terminal locking (similar to the lock command). It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for the matching password as confirmation and if match occurs, it must lock the keyword until a

Dept.of MCA, RVCE 42

Page 43: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

matching password is entered again by the user, Note that the script must be written to disregard BREAK, control-D. No time limit need be implemented for the lock duration

Lab Cycle 5:

4a Write a shell script that accept one or more filenames as argument and convert all of them to up-percase, provided they exist in current directory.

b Write a shell script that displays all the links to a file specified as the first argument to the script. The second argument, which is optional, can be used to specify in which the search is to begin. If this second argument is not present, the search is to begin in current working directory. In either case, the starting directory as well as all its subdirectories at all levels must be searched. The script need not include any error checking.

Lab Cycle 6:

5a. Write a shell script that accepts filenames as arguments and displays its creation time if the file ex-ists and if the file does not exists, send output error message.

b. Write a shell script to display the calendar for current month with current date replaced by * or ** depending on whether the date has one digit or two digits.

6a. Write a shell script to find a file/s that matches a pattern given as command line argument in the home directory, display the contents of the file and copy the file into the directory ~/mydir.

b. Write a shell script to list all the files in a directory whose filename is at least 10 characters. (Use expr command to check the length).

Lab Cycle 7:7a. Write a shell script that gets executed and displays the message either “Good Morning” or “Good

Afternoon” or “Good Evening” depending upon time at which the user logs in.

b. Write a shell script that accept a list of filenames as its argument, count and report occurrence of each word that is present in the first argument file on other argument files.

Lab Cycle 8:8a. Write a shell script that determine the period for which a specified user is working on system and dis -

play appropriate message.

b. Write a shell script that reports the logging in of a specified user within one minute after he/she log in. The script automatically terminate if specified user does not log in during a specified period of time.

Dept.of MCA, RVCE 43

Page 44: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

Lab Cycle 9:9a. Write a shell script that accepts the file name, starting and ending line number as an argument and

display all the lines between the given line number.

b. Write a shell script that folds long lines into 40 columns. Thus any line that exceeds 40 characters must be broken after 40th, a “\” is to be appended as the indication of folding and the processing is to be continued with the residue. The input is to be supplied through a text file created by the user.

Lab Cycle 10:10a. Write an awk script that accepts date argument in the form of mm-dd-yy and displays it in the form

of day, month, and year. The script should check the validity of the argument and in the case of error, display a suitable message.

b. Write an awk script to delete duplicated line from a text file. The order of the original lines must re-main unchanged.

Lab Cycle 11:11a. Write an awk script to find out total number of books sold in each discipline as well as total book

sold using associate array down table as given below.Electrical 34Mechanical 67Electrical 80Computer Science 43Mechanical 65Civil 98Computer Science 64

b. Write an awk script to compute gross salary of an employee according to rule given below.If basic salary is < 10000 then HRA=15% of basic & DA=45% of basic.

If basic salary is >=10000 then HRA=20% of basic & DA=50% of basic.

Lab Cycle 12:

To Complete Back Logs, if any and Revision

.

Dept.of MCA, RVCE 44

Page 45: 13MCA17- Unix Laboratory Manual 2013

Unix Programming Laboratory Manual I Semester MCA 2013-14

NOTE:

Write the program(s) of the current lab cycle in the data sheet prior to coming to the lab.

On the left side of the record the students are required to explain the syntax and meaning of the

commands, programming constructs used in the program.

Errors encountered during the compilation must be written in the data sheet first, along with the

solutions to correct the errors and the same to be written on the left side of the record.

The complete question, Program source code and a minimum of 2 outputs with the validations,

must be written on the right hand side of the record.

Program outcome- the unix concepts learnt in the current program, along with their application

areas must be written on the left side of the record, for every program.

Any backlogs to be completed only after finishing the regular defined lab cycles.

Lab Evaluation Scheme

Internal Evaluation : 50 marks

Record Marks : 20 marks

Lab Internals : 30 marks

Programming Skills: 10 marks

Exam Evaluation : 50 marks

Viva Marks : 15%

Write up : 15%

Execution : 70%

Faculty in-charge Faculty in-charge Director

I Sem ‘A’ Section I Sem ‘B’ Section

Dept.of MCA, RVCE 45