sem 3 unix

63
1.(a) Write a Shell program to concatenate the contents of 2 files. SCRIPT ----------- #! /bin/sh clear echo "Enter the first file name" read a echo "Enter the second file name" read b echo "Contents in" $a cat $a echo "Contents in" $b cat $b cat $a $b > file3 cat file3 sleep 5 OUTPUT ------------- Enter the first file name /home/mcai/y65532/shell/f1 Enter the second file name /home/mcai/y65532/shell/f2 Contents in /home/mcai/y65532/shell/f1 this is my first shell program Contents in /home/mcai/y65532/shell/f2 this is my second shell program contents in file3 this is my first shell program this is my second shell program 1

Upload: rakeshyellapragada

Post on 24-Apr-2015

802 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sem 3 Unix

1.(a) Write a Shell program to concatenate the contents of 2 files.

SCRIPT-----------#! /bin/shclearecho "Enter the first file name"read aecho "Enter the second file name"read becho "Contents in" $acat $aecho "Contents in" $bcat $bcat $a $b > file3cat file3sleep 5

OUTPUT-------------Enter the first file name/home/mcai/y65532/shell/f1

Enter the second file name/home/mcai/y65532/shell/f2

Contents in /home/mcai/y65532/shell/f1this is my first shell program

Contents in /home/mcai/y65532/shell/f2this is my second shell program

contents in file3this is my first shell programthis is my second shell program

1

Page 2: Sem 3 Unix

1.(b) Write a Shell command to list all the files in the /tmp directory Owned by the user root.

SCRIPT------[y65532@aditya unix1]$ ls -l /tmp | grep "root"drwx------ 2 root root 16384 Dec 19 2003 lost+founddrwx------ 2 root root 8192 Oct 20 19:47 orbit-root-rw------- 1 root root 0 Oct 30 08:19 session_mm.sem

1.(c) Construct a pipeline to count number of users currently logged in.

SCRIPT------[y65532@aditya unix1]$ echo The number of users logged are: `who|wc -l`The number of users logged are: 23

2

Page 3: Sem 3 Unix

2.(a) Use grep command to find each line of a given file that contains some required pattern. SCRIPT----------#! /bin/shecho Enter the word:read wordecho Enter the filename:read fileecho The pattern lines are:grep $word $file

OUTPUT-------------[y65532@aditya unix1]$ sh 2aEnter the word:echoEnter the filename:1The pattern lines are:echo "Enter the first file name"echo "Enter the second file name"echo "Contents in" $aecho "Contents in" $b

2.(b) Compare two files, displaying all differences in another file.

SCRIPT ------------#! /bin/shecho Enter first filename:read aecho Enter second filename:read becho Contents in $a file:cat $asleep 1echo Contents in $b file:cat $bechodiff $a $b >temp2echo The difference is:cat temp2

3

Page 4: Sem 3 Unix

OUTPUT------------[y65532@aditya unix1]$ sh 2bEnter first filename:1Enter second filename:2aContents in 1 file:#! /bin/sh

clearecho "Enter the first file name"read aecho "Enter the second file name"read becho "Contents in" $acat $aecho "Contents in" $bcat $bcat $a $b > file3cat file3sleep 5

Contents in 2a file:#! /bin/shclearecho Enter the word:read wordecho Enter the filename:read fileecho The pattern lines are:grep $word $file

The difference is:2d1<4,14c3,8< echo "Enter the first file name"< read a< echo "Enter the second file name"< read b< echo "Contents in" $a< cat $a< echo "Contents in" $b< cat $b

4

Page 5: Sem 3 Unix

< cat $a $b > file3< cat file3< sleep 5---> echo Enter the word:> read word> echo Enter the filename:> read file> echo The pattern lines are:> grep $word $file

5

Page 6: Sem 3 Unix

3. Write a Shell command to sort the / etc/passwd file, place the Results in the file called foo.

SCRIPT----------[y65532@aditya unix1]$ sort /etc/passwd >foo

6

Page 7: Sem 3 Unix

4. Write a Shell program to reverse a given five-digit number.

SCRIPT----------#!/bin/shecho Enter any numberread nrev=0for((i=0;n!=0;i++))do{ r=`expr $n % 10` rev=`expr $rev \* 10 + $r` n=`expr $n / 10`}doneecho The reverse of given number is $revsleep 2

OUTPUT-----------Enter any number:12345The reverse of the given number is: 54321

7

Page 8: Sem 3 Unix

5. (a) Print the numbers from 1 to 10 .

SCRIPT----------#! /bin/shecho Enter the value of n:read necho The numbers are:for (( i=1; i<=n; i++))do echo $idone

OUTPUT-----------Enter the value of n:6The numbers are:1 2 3 4 5 6

5. (b) Write a Shell script that reports how many bytes are used by Regular files in a directory.

SCRIPT----------#!/bin/bashecho Enter the directory nameread aif [ -d $a ]then bytecount=0 for i in `ls $a` do if [ -f $i ] then bytes=`ls -l $a/$i|tr -s ' '|cut -d ' ' -f5` bytecount=`expr $bytecount + $bytes` fi done echo bytes in use by regular files is $bytecountelse echo $a is not a directoryfisleep 2

8

Page 9: Sem 3 Unix

OUTPUT-----------[y65532@aditya unix1]$ sh 5bEnter the directory name/home/mcai/y65532/unix1bytes in use by regular files is 11388

9

Page 10: Sem 3 Unix

6. Write a shell script to mail a letter to the list of users in a file called"mylist" .

SCRIPT----------#!/bin/shecho "Enter a file name"read filefor person in `cat mylist`do mail -s "Hi! How are you ?" $person <$file echo "mail sent to " $persondonesleep 2

OUTPUT------------Enter a file name mylistmail sent to y55555mail sent to y55552mail sent to y55558

10

Page 11: Sem 3 Unix

7. Create a script file that backup file names starting with letter 'f' with Extension '. bak', creating a directory 'backup' .

SCRIPT----------#!/bin/shecho "Enter a directory name"read ddmkdir $ddfor i in `ls f*.bak`do cp $i $dd/$idoneecho backup is donels -l $ddsleep 2

OUTPUT------------Enter a directory nametemp1backup is donetotal 4-rw-r--r-- 1 y55555 mcai 17 Sep 16 12:42 ff.bak

11

Page 12: Sem 3 Unix

8. (a) Set the executable permission on all plane files.

SCRIPT-----------#!/bin/shecho Enter the directory name

read fnamefor n in *do chmod -x $ndone

OUTPUT------------Enter the directory name/home/mcai/y65532/unix1

8.(b) Write a shell script called 'quiz' that confirms the shell that u are Using.

SCRIPT----------#!/bin/bashclearecho Enter the shell nameread nameif [ $name = $SHELL ]then echo This is the current shellelse echo This is not the current shellfi

OUTPUT------------[y65532@aditya unix1]$ sh 8bEnter the shell name/bin/bashThis is the current shell

12

Page 13: Sem 3 Unix

9. (a) Write a shell script to check whether given user is logged or not.

SCRIPT----------echo To find out whether the given user is logged or notecho Enter the numberread numif who | grep $numthen echo logged inelse echo logged outfi

OUTPUT------------To find out whether the given user is logged or notEnter the numbery55555y55555 pts/57 Oct 31 10:42 (123.0.55.23)logged in

9. (b) Write a shell script to display a message, when the given user Logged in.

SCRIPT----------#!/bin/bashclearecho Enter the lognameread namewho | grep $name >tmpif [ $? -eq 0 ]then echo hai, this is a message to $nameelse echo the given user is not loogedfi

OUTPUT------------[y65532@aditya unix1]$ sh 9bEnter the lognamey55555hai, this is a message to y55555

13

Page 14: Sem 3 Unix

10. Write a shell script that performs arithmetic operations on the Given numeric arguments.

SCRIPT-----------#! bin/sh#To perform arithmetic operationsecho Enter the valuesread value1 value2echo Addition of two numbers is `expr ${value1} + ${value2}` echoecho Subtraction of two numbers is `expr ${value1} - ${value2}`echoecho Multiplication of two numbers is `expr ${value1} \* ${value2}`echoecho Division of two numbers is `expr ${value1} / ${value2}`echo

OUTPUT-----------[y65532@aditya unix1]$ sh 10Enter the values6 4Addition of two numbers is 10Subtraction of two numbers is 2Multiplication of two numbers is 24Division of two numbers is 1

14

Page 15: Sem 3 Unix

11. Obtain a list of users who have unread mail (mail size > 0)

SCRIPT----------

#!/bin/shecho '***************************************************'echo List of users who have unread mailecho '***************************************************'echols -l /var/spool/mail | tr -s ' ' | cut -f 5,9 -d " " | awk ' ( $1 > 0 ) { print $2 "has unread mail" } 'sleep 2

OUTPUT-----------[y65532@aditya unix1]$ sh 11

****************************************** List of users who have unread mail******************************************

glakshmihas unread mailkiranhas unread mailmca1has unread mailmmadhavihas unread mailroothas unread mailsivaramhas unread mail

t02has unread mailt03has unread maily55506has unread maily55507has unread maily55509has unread maily55510has unread maily55511has unread mail

15

Page 16: Sem 3 Unix

12.(a) Write a shell script to greet any of your 4 friends with a for loop, Proceeded by the string "Hi".

SCRIPT----------#!/bin/bashecho Hai to everyonefor i in y65532 y55552 y55555do echo $i hidone

OUTPUT-----------[y65532@aditya unix1]$ sh 12aHai to everyoney65532 hiy55552 hiy55555 hi

12.(b)Write a shell script to greet any of your 4 friends with a for loop, Preceded by the string "Hi", accepting friends names from the command prompt.

SCRIPT----------echo Hai to everyonefor i in $@do echo $1 hi shiftdone

OUTPUT------------[y65532@aditya unix1]$ sh 12b y55555 y55558 y55546Hai to everyoney55555 hiy55558 hiy55546 hi

16

Page 17: Sem 3 Unix

13. Write a Shell program to sort given numbers in ascending order.

SCRIPT-----------#!/bin/shecho Enter the value of nread necho Enter the elements into the array:for (( i=1; i<=$n; i++ ))do echo Enter the value of $i read a[$i]donefor (( i=1;i<=$n-1; i++))do for (( j=1;j<=$n-$i;j++ )) do k=`expr $j + 1` if [ ${a[$j]} -gt ${a[k]} ] then temp=${a[$j]} a[$j]=${a[k]} a[k]=$temp fi donedoneecho The sorted elements are:for (( i=1;i<=$n;i++ ))do printf "%3d" ${a[$i]}doneechosleep 2

OUTPUT-----------[y65532@aditya unix1]$ sh 13

Enter the value of n4Enter 4 elements into the array:8124

17

Page 18: Sem 3 Unix

The sorted elements are: 1 2 4 8

18

Page 19: Sem 3 Unix

14. Write a Shell program to exchange the values of two variables.

SCRIPT----------#!/bin/bashecho Enter any two numbersread a becho The given numbers before swapping areecho $a $bt=$aa=$bb=$techo The given numbers after swapping areecho $a $bsleep 2

OUTPUT-----------[y65532@aditya unix1]$ sh 14Enter any two numbers5 8The given numbers before swapping are5 8The given numbers after swapping are8 5

19

Page 20: Sem 3 Unix

15. Find all lines in a file with words longer than four characters, Assuming that words are separated by spaces except at the beginning or at the end.

SCRIPT----------#!/bin/shecho Enter file nameread fnamen=`cat $fname |wc -l`i=1while [ $i -le $n ]do line=`cat $fname |head -$i |tail +$i` words=`echo $line|tr -s " "|wc -w` w=1 while [ `expr $w - 1 ` -lt $words ] do str=`echo $line|tr -s " "|cut -d " " -f$w` count=`echo $str|wc -c` count=`expr $count - 1` if [ $count -gt 4 ] then echo $i $line break fi w=`expr $w + 1` done i=`expr $i + 1`donesleep 2

OUTPUT------------Enter file namep151 echo Enter file name2 read fname3 n=`cat $fname |wc -l`5 while [ $i -le $n ]7 line=`cat $fname |head -$i |tail +$i`8 words=`echo $line|tr -s " "|wc -w`10 while [ `expr $w - 1` -lt $words ]12 str=`echo $line|tr -s " "|cut -d " " -f$w`13 count=`echo $str|wc -c`14 count=`expr $count - 1`

20

Page 21: Sem 3 Unix

15 if [ $count -gt 4 ]17 echo $i $line18 break20 w=`expr $w + 1`22 i=`expr $i + 1`

21

Page 22: Sem 3 Unix

16. Write a Shell script to sort the given numbers in descending order Using bubble sort algorithm.

SCRIPT----------#!/bin/bashecho Enter the array sizeread necho Enter the array elementsfor (( i=0; i<$n; i++ ))do read a[$i]doneecho The elements before sorting arefor (( i=0; i<$n; i++ ))do echo ${a[$i]}donefor (( i=0; i<$n; i++ ))do for (( j=0; j<$n; j++ )) do if [ ${a[$i]} -gt ${a[$j]} ] then t=${a[$i]} a[$i]=${a[$j]} a[$j]=$t fi donedoneecho The elements after sorting arefor (( i=0; i<$n; i++ ))do printf "%3d" ${a[$i]}doneechosleep 2

OUTPUT------------[y65532@aditya unix1]$ sh 16

Enter the array size5

22

Page 23: Sem 3 Unix

Enter the array elements1 2 8 6 4

The elements before sorting are1 2 8 6 4

The elements after sorting are 8 6 4 2 1

23

Page 24: Sem 3 Unix

17. Write a Shell program to display the digits, which are in the odd Positions in a given five-digit number.

SCRIPT----------#!/bin/bashecho Enter any five digited numberread ncount=0t=$nwhile [ $t -gt 0 ]do count=`expr $count + 1` t=`expr $t / 10`done

if [ $count -ne 5 ]then echo The entered number is not a five digited numberfii=0while [ $n -gt 0 ]do r=`expr $n % 10` a[$i]=$r i=`expr $i + 1` n=`expr $n / 10`done

for (( i=5; i>=0; i-- ))sdo if [ `(expr $i % 2)` -eq 0 ] then printf "%3d" ${a[$i]} fidonesleep 2

OUTPUT------------[y65532@aditya unix1]$ sh 17Enter any five digited number124451 4 5

24

Page 25: Sem 3 Unix

18. Write a Shell script to find the largest number among the three given numbers.

SCRIPT-----------#!/bin/bashecho Enter three numbersread a b cif [ $a -gt $b -a $a -gt $c ]then echo $a is the greatest numberelif [ $b -gt $c -a $b -gt $a]

then echo $b is the greatest numberelse echo $c is the greatest numberfi

sleep 2

OUTPUT------------[y65532@aditya unix1]$ sh 18a

Enter three numbers8 9 19 is the greatest number

25

Page 26: Sem 3 Unix

19. Write a Shell program to search for a given number from a list of Numbers provided using binary search method.

SCRIPT----------#!/bin/bashecho enter array sizeread necho enter array elementsfor (( i=0;i<$n;i++ ))do read a[$i]doneecho Enter element to be searched:read eleflag=0low=0high=`expr $n - 1`while [ $low -le $high ]domid=`expr $low + $high`mid=`expr $mid / 2`if [ ${a[$mid]} -eq $ele ]then flag=1 breakfiif [ ${a[$mid]} -lt $ele ]thenhigh=`expr $mid - 1`fiif [ ${a[$mid]} -gt $ele ]thenlow=`expr $mid + 1`fidoneif [ $flag -eq 1 ]thenecho The element is found in the arrayelseecho The element is not foundfisleep 2

26

Page 27: Sem 3 Unix

OUTPUT------------[y65532@aditya unix1]$ s 19bash: s: command not found[y65532@aditya unix1]$ sh 19enter array size4enter array elements1582Enter element to be searched:5The element is found in the array

27

Page 28: Sem 3 Unix

20. Write grep command to find each line of the given file that contains some required pattern and display the number of occurrences.

SCRIPT----------[y65532@aditya unix1]$ grep -c echo 133

28

Page 29: Sem 3 Unix

21. Create a file with delimiter. First name, last name, DOB, address,pincode.

SCRIPT----------#!/bin/shecho Enter the first nameread fnameecho Enter the last nameread lnameecho Enter the date of birthread dobecho Enter the addressread addecho Enter the pincoderead pinecho Enter the delimiterread delecho The output with delimiter is:echo $fname $del $lname $del $dob $del $add $del $pin >addcat addsleep 2

OUTPUT-----------[y65532@aditya unix1]$ sh 21Enter the first namehariEnter the last namekishoreEnter the date of birth8-12-1985Enter the addressvijayawadaEnter the pincode520001Enter the delimiter:::The output with delimiter is:hari ::: kishore ::: 8-12-1985 ::: vijayawada ::: 520001

29

Page 30: Sem 3 Unix

22. Write script that will ask user, fullname (first, middle, last name) greet user by first name. Ask users DOB and calculate users age, print users home directory.

SCRIPT----------#!/bin/shecho Enter the first nameread firstecho Enter the middle nameread middleecho Enter the last nameread lastecho "Hai!" $firstecho Enter the date of birth yearread dobecho The present year isd=`date | cut -d " " -f6`echo $dage=`expr $d - $dob`echo The age is: $ageecho The home directory is $HOMEsleep 2

OUTPUT-----------[y65532@aditya unix1]$ sh 22Enter the first namehariEnter the middle namekishoreEnter the last namegHai! hariEnter the date of birth year1985The present year is2006The age is: 21The home directory is /home/mcai/y65532

30

Page 31: Sem 3 Unix

23. Change all occurrences of "P.B.Siddhartha College of Arts and Science" to "P.G.Centre of P.B.Siddhartha" present in a file.

SCRIPT----------#!/bin/shecho Enter the file nameread fecho Contents of the filecat $fechoecho Contents after replacementsed 's/P.B.Siddhartha/P.G. Center of Siddhartha/g' $f

OUTPUT------------[y65532@aditya unix1]$ sh 23Enter the file nametempContents of the fileWelcome to P.B.Siddhartha CollegeP.B.Siddhartha CollegeP.G.Centre

Contents after replacementWelcome to P.G. Center of Siddhartha CollegeP.G. Center of Siddhartha CollegeP.G.Centre

31

Page 32: Sem 3 Unix

24. Replace all occurrences of " CSI and P.B.Siddhartha" with "P.B.Siddhartha and CSI".

SCRIPT----------#!/bin/shecho Enter the file nameread fecho Contents of the filecat $fechoecho Contents after replacementcat $f|sed 's/P.B.Siddhartha and CSI/CSI and P.B.Siddhartha/g' > $fcat $f

32

Page 33: Sem 3 Unix

25. Write an awk script, which will return the factorial of a user supplied number.

SCRIPT----------{ a=$0 f=1; for(i=2;i<=a;i++) f=f*i; print "Factorial is " f}

OUTPUT------------[y65532@aditya unix1]$ awk -f 256 (Press ctr + d)Factorial is 720

or

[y65532@aditya unix1]$ awk -f 25 25inputFactorial is 720Factorial is 5040Factorial is 40320

33

Page 34: Sem 3 Unix

26. Create a script that sleeps for 10 minutes. Excute the script so that it is running ever after user has logged out. Determine the process id of that script and kill it.

SCRIPT----------# contents in sleepscript.sh file are as follows: sleep 10m

main script------------#!/bin/sh# Script that runs a script that sleeps for 10 minutes in background# And then gets pid for that process to kill it./sleepscript.sh &echo $! >pid

echo process id to be killed `cat pid`... press enterreadk=`cat pid`echo killing $k...echo `ps -ae|grep $k`kill $kecho done

OUTPUT------------[y65532@aditya lab]$ sh lab26.shprocess id to be killed 24004... press enter

killing 24004...24004 pts/2 00:00:00 shdone

34

Page 35: Sem 3 Unix

27. Print out a report of users who have accounts on the system and their login shell.

SCRIPT----------#!/bin/bashecho The users who have account on the system and their login shells are:cat /etc/passwd | cut -f1,7 -d: | more -dsleep 2

OUTPUT-----------[y65532@aditya lab]$ sh lab27.shThe users who have account on the system and their login shells are:root:/bin/bashbin:/sbin/nologindaemon:/sbin/nologinadm:/sbin/nologinlp:/sbin/nologinsync:/bin/syncshutdown:/sbin/shutdownhalt:/sbin/haltmail:/sbin/nologinnews:uucp:/sbin/nologinoperator:/sbin/nologingames:/sbin/nologingopher:/sbin/nologinftp:/sbin/nologinnobody:/sbin/nologin

35

Page 36: Sem 3 Unix

28. Write a shell script that will take non-zero (variable) command line arguments and print them in reverse order. Input

myscript arg1 arg2 ... arg5 Output

arg5 arg4 ... arg1

SCRIPT:----------#!/bin/bashstr=""while [ $# -gt 0 ]dostr=`echo $1 $str`shiftdoneecho $strsleep 2

OUTPUT:------------[y65532@aditya lab]$ sh lab28.sh arg1 arg2 2 3 4 a bb a 4 3 2 arg2 arg1

36

Page 37: Sem 3 Unix

29. Write a shell script that will compute the value raised to a power Input : power m n Output : m raised to the power of n Note: m raised to the power of 0 is 1

SCRIPT:-----------#!/bin/bashif [ $# -ne 2 ]thenecho Invalid number of argumentsexitfib=$1sum=1for ((i=0; i<$2; i++ ))dosum=`expr $sum \* $b`doneecho The exponential value is: $sumsleep 2

OUTPUT:-----------[y65532@aditya lab]$ sh lab29.sh 3 5The exponential value is: 243

[y65532@aditya lab]$ sh lab29.shInvalid number of arguments[y65532@aditya lab]$ sh lab29.sh 1 0The exponential value is: 1

37

Page 38: Sem 3 Unix

30. Write a shell script convert that will convert a given constant in a specified base into the specified base using functions.

Input Format: convert number currentbase newbase Example: convert A1034 16 8

Output for above example: 02410064

SCRIPT:-----------#!/bin/sh# Shell script to convert a given constant from specified base to specified baseusage() {# function that prints usage aand exits echo Invalid arguments echo Usage: $0 number from-base to-base echo Maximum base supported is 16, minimum is 2 echo " " exit}

digittonum() {# function that converts characters in a given base (upto 16) to decimal equivalent if [ $digit = A ] ; then digit=10 elif [ $digit = B ] ; then digit=11 elif [ $digit = C ] ; then digit=12 elif [ $digit = D ] ; then digit=13 elif [ $digit = E ] ; then digit=14 elif [ $digit = F ] ; then digit=15 fi}

numtodigit() {# function that converts a number to its base represented character (upto base 1

if [ $digit -eq 10 ] ; then digit=A elif [ $digit -eq 11 ] ; then digit=B

38

Page 39: Sem 3 Unix

elif [ $digit -eq 12 ] ; then digit=C elif [ $digit -eq 13 ] ; then digit=D elif [ $digit -eq 14 ] ; then digit=E elif [ $digit -eq 15 ] ; then digit=F fi}

converttodec() {# function that converts $number from base $2 to its decimal equivalent pow=1 pos=`echo $number|wc -c` pos=`expr $pos - 1` sum=0 while [ $pos -ne 0 ] ; do digit=`echo $number|cut -c $pos` pos=`expr $pos - 1` number=`echo $number|cut -c 1-$pos` digittonum mul=`expr $digit \* $pow` sum=`expr $sum + $mul` pow=`expr $pow \* $from_base` done base_10=$sum}converttorequired() {# function that converts $base_10 to its required base echo to convert $base_10 from base 10 to base $to_base number=$base_10 sum="" while [ $number -ge $to_base ] ; do digit=`expr $number % $to_base` numtodigit sum=$digit$sum number=`expr $number / $to_base` done base_n=$number$sum}

if [ $# -ne 3 ] ; then usagefiif [ $2 -lt 2 -o $2 -gt 16 ] ; then

39

Page 40: Sem 3 Unix

usagefiif [ $3 -lt 2 -o $3 -gt 16 ] ; then usagefi

number=$1from_base=$2to_base=$3base_10=0base_n=0converttodececho Intermediate result: Equivalent of $1 in base $2 is $base_10 in base 10converttorequiredecho Final result is: $base_necho

OUTPUT:-----------[y65532@aditya unix]$ sh numconvert.sh A1034 16 8Intermediate result: Equivalent of A1034 in base 16 is 659508 in base 10to convert 659508 from base 10 to base 8Final result is: 2410064

40

Page 41: Sem 3 Unix

31. Calculate the compound interest where the amount, interest rate and time are specified Input: compinterest amount interest time

SCRIPT:----------#!/bin/bashif [ $# -ne 3 ]thenecho Invalid number of argumentsfip=$1ra=$2n=$3br=`echo $ra / 100 | bc -l`br=`echo $br + 1 | bc -l`pow=1for ((i=1; i<=$n; i++))dopow=`echo $pow \* $br|bc -l`doneci=`echo $p \* $pow | bc -l`echo The compound interest is: `echo $ci - $p|bc -l`sleep 2

OUTPUT:------------[y65532@aditya lab]$ sh lab31.sh 1000 2 33The compound interest is: 922.23140394315183157000

41

Page 42: Sem 3 Unix

32. Identify the top 10 disk usage files in /usr/bin

[y65532@aditya bin]$ du * | sort -rn |head4244 xemacs-21.1.143440 doxygen3428 emacs-20.73428 emacs3360 gs3232 ddd3228 emacs-nox3068 pine2552 jikes2068 nwadmin

42

Page 43: Sem 3 Unix

33. Write a shell script that determines if a given input (numeric and character string) is a palindrome.

SCRIPT:-----------#!/bin/shecho Enter any name or number:read strrstr=`echo $str | rev`if [ $str = $rstr ]thenecho The given item is palindromeelseecho The given item is not palindromefisleep 2

OUTPUT:------------[y65532@aditya lab]$ sh lab33.shEnter any name or number:121The given item is palindrome

[y65532@aditya lab]$ sh lab33.shEnter any name or number:malayalamThe given item is palindrome

Enter any name or number:abcdThe given item is not palindrome

43

Page 44: Sem 3 Unix

34. Write a script to find the largest value from among a set of values in an input file and delete it from an array. Print out the values and the non-zero frequency of each item.

SCRIPT:-----------#!/bin/sh# To copy contents of file into array and display arrayechoecho The elements in the file are:n=0for i in `cat temp`do a[$n]=$i printf "%3d" ${a[$n]} let n++doneecho

# To find the maximum of the arraymax=0for((i=0; i<n; i++))do if [ $max -lt ${a[$i]} ] then max=${a[$i]} fidoneechoecho The maximum element in the file is: $max

# To remove the maximum element from the arrayfor((i=0; i<n; i++))do if [ $max -eq ${a[$i]} ] then for((k=$i; k<n; k++)) do a[$k]=${a[$k+1]} done n=`expr $n - 1` i=`expr $i - 1` fidone

# To check whether the max is the only element in the array

44

Page 45: Sem 3 Unix

if [ $n -eq 0 ]then echo There are no elements in the array exitfi

# To display array elements after deleting maxechoecho Array elements after deleting is:for((i=0; i<n; i++))do printf "%3d" ${a[$i]}doneecho

# To create an array t to store frequenciesfor((k=0; k<max; k++))do t[$k]=0done

# To update the frequency of array elements in array tfor((i=0; i<n; i++))do t[${a[$i]}]=`expr ${t[${a[$i]}]} + 1`done

# To display the frequency of the non-zero frequency of eacechoecho The frequency of elements is:for((i=0; i<max; i++))do if [ ${t[$i]} -gt 0 ] then echo The frequency of $i is: ${t[$i]} fidonesleep 2

OUTPUT:------------[y65532@aditya lab]$ sh lab34.sh

The elements in the file are: 5 6 7 8 5 6 4

45

Page 46: Sem 3 Unix

The maximum element in the file is: 8

Array elements after deleting is: 5 6 7 5 6 4

The frequency of elements is:The frequency of 4 is: 1The frequency of 5 is: 2The frequency of 6 is: 2The frequency of 7 is: 1

46

Page 47: Sem 3 Unix

35. Write a script to calculate the age of a user to the nearest hour.

SCRIPT:-----------{ print $1 ", your date of birth is " $2 btimestamp=mktime($2); print "Timestamp for your birthday is " btimestamp stimestamp=systime(); print "Current system timestamp is " stimestamp dtimestamp=stimestamp-btimestamp; print "Difference in timestamps is " dtimestamp years=strftime("%Y",dtimestamp); years=years-1970 print "Your are " years " Years " strftime("%m",dtimestamp) " Months "strftime("%d",dtimestamp) " Days " strftime("%H",dtimestamp) " Hours "strftime("%M",dtimestamp) " Minutes " strftime("%S",dtimestamp) " Seconds old (and counting...)"}

OUTPUT:------------[y65532@aditya y65532]$ awk -F ':' -f 35Hari Kishore:1985 08 02 14 05 30Hari Kishore, your date of birth is 1985 08 02 14 05 30Timestamp for your birthday is 491819730Current system timestamp is 1162374279Difference in timestamps is 670554549Your are 21 Years 04 Months 02 Days 06 Hours 39 Minutes 09 Seconds old (and counting...)

or

[y65532@aditya y65532]$ awk -F ':' -f 35 35inputHari Kishore, your date of birth is 1985 02 08 14 05 30Timestamp for your birthday is 476699730Current system timestamp is 1162374208Difference in timestamps is 685674478Your are 21 Years 09 Months 24 Days 06 Hours 37 Minutes 58 Seconds old (and counting...)

47

Page 48: Sem 3 Unix

36. Read in input file name and output file name and convert the Characters into inverse case.

[y65532@aditya lab]$ cat lab27.sh | tr [a-zA-Z] [A-Za-z] >output[y65532@aditya lab]$ cat output#!/BIN/BASHECHO tHE USERS WHO HAVE ACCOUNT ON THE SYSTEM ARE:

48

Page 49: Sem 3 Unix

37. Write a shell program to concatenate the contents of two files Without using the cat command.

SCRIPT:----------#!/bin/shecho Enter the first filename:read f1echo Enter the second filename:read f2l1=`wc -l $f1|tr -s " "|cut -d" " -f2`head -$l1 $f1 >templ2=`wc -l $f2|tr -s " "|cut -d" " -f2`head -$l2 $f2 >>tempcat temp

OUTPUT:-----------[y65532@aditya lab]$ sh lab38.shEnter the first filename:itemsEnter the second filename:pidCarrots 5 14.00Eggs 12 1.25Bread 6 12.0024004

49

Page 50: Sem 3 Unix

38. Display username and idle time for each user who is logged in.

[y65532@aditya lab]$ who --idle | tr -s " "|cut -f1,6 -d" "y55552 01:33y65532 .y55731 00:03y55541 00:03y55555 .y55506 01:02

50

Page 51: Sem 3 Unix

39. Write a shell script to reverse a given number Input 23619 Output 91632

SCRIPT:-----------#!/bin/bashecho Enter any number:read nrev=0while [ $n -ne 0 ]dora=`expr $n % 10`rev=`expr $rev \* 10 + $ra`n=`expr $n / 10`doneecho The reverse of given number is: $revsleep 2

OUTPUT:------------[y65532@aditya lab]$ sh lab40.shEnter any number:23619The reverse of given number is: 91632

51

Page 52: Sem 3 Unix

40. Write a shell script that calls a function fact that will compute the factorial of a specified input

SCRIPT:----------#!/bin/shfactorial(){ fact=1 while [ $n -gt 0 ] do fact=`expr $fact \* $n` n=`expr $n - 1` done}echo Enter any number:read nfactorial $necho The factorial of given number is: $factsleep

OUTPUT:-------------[y65532@aditya lab]$ sh lab41.shEnter any number:5The factorial of given number is: 120

52

Page 53: Sem 3 Unix

53