CSE ([email protected] II-Sem) EXP-13 1. Write a shell script to check whether a particular user has logged in or not. If he has logged in, also check whether he has eligibility to receive a message or not.

[KRISHNASAI@localhost exp13]$ vi 1check.sh function checkuser { f=0; echo "------" for u in `who | cut -f1 -d" " | sort | uniq` do who>userlist if [ $u = $1 ] then echo "$1 is available" echo "$1 is logged in " `grep -c $1 userlist` " terminals " echo "$1 is logged at" grep "$1" userlist|cut -d"(" -f2 f=`expr $f + 1` fi done if [ $f -lt 1 ] then echo "user not available" fi } if [ -z $1 ] then echo "Enter username: " read k checkuser $k echo "------" exit 1 fi checkuser $1 exit 1 Output: [KRISHNASAI@exp13]$ sh 1check.sh [KRISHNASAI@exp13]$ sh 1check.sh Enter username: Enter username: KRISHNASAI krishna ------KRISHNASAI is available krishna is available KRISHNASAI is logged in 1 terminals krishna is logged in 2 terminals KRISHNASAI is logged at krishna is logged at 192.168.1.191) 192.168.1.166) ------192.168.1.118) ------

bphanikrishna.wordpress.com FOSSLAB Page 1 of 38 CSE ([email protected] II-Sem) EXP-13 2. Write a shell script to accept the name of the file from standard input and perform the following tests on it a) File executable b) File readable c) File writable d) Both readable & writable [krishnasai@exp13]$ vi 2fp.sh Output: echo enter a file name read file [krishnasai@exp13]$sh 2fp.sh if [ -e $file ] enter a file name then h1 echo "$file exists" h1 exists if [ -f $file ] h1 is an ordinary file then h1 does not have read access echo "$file is an ordinary file" h1 has write permission if [ -r $file ] h1 has execute permission then echo "$file has read access" else echo "$file does not have read access" fi if [ -w $file ] then echo "$file has write permission" else echo "$file does not have write permission" fi if [ -x $file ] then echo "$file has execute permission" else echo "$file does not have execute permission" fi if [ -r $file ] && [ -w $file ] then echo "$file has both read and write operations" fi elif [ -d $file ] then echo "$file is a directory" fi else echo "$file does not exist" fi

bphanikrishna.wordpress.com FOSSLAB Page 2 of 38 CSE ([email protected] II-Sem) EXP-13 3. Write a shell script which will display the username and name who login recently in to the unix system

[KRISHNASAI@Host exp13]$ vi 3.ut.sh today=$(date +"%A") tday=$(date +"%d-%B-%Y") time=$(date +"%r ||%z ") echo "Today is :$today" echo "Today date is :$tday" echo "Time :$time" who>userlist i=0 for u in `who|cut -d" " -f1` do i=`expr $i + 1` done echo "Total number of users are : $i " echo "login user details in `date +"%D %H-%M-%S "`" echo "------" echo "USER TERMINAL" echo "======" who|cut -d" " -f1>u who|cut -d"(" -f2>t paste u t echo "------" Syntax Time only [KRISHNASAI@Host exp13]$ sh 3.ut.sh date +"%FORMAT" Today is :Tuesday Type the following Today date is :10-March-2015 $ date +"%m-%d- command: Time :05:58:18 PM ||+0530 %y" $ date +"%T" Total number of users are : 2 Sample output: login user details in 03/10/15 17-58-18 Outputs: ------02-27-07 USER TERMINAL 19:55:04 ======CSESTAFF 192.168.1.219) 149P1A0521 192.168.1.118) ------

bphanikrishna.wordpress.com FOSSLAB Page 3 of 38 CSE ([email protected] II-Sem) EXP-13

4. Write a shell script to find no. of files in a directory

[KRISHNASAI@localhost exp13]$ vi 4.sh f=0 d=0 for i in `ls -l|cut -c 1` do if [ $i = "-" ] then f=`expr $f + 1` elif [ $i = "d" ] then d=`expr $d + 1` fi done echo no of ordinary files are $f echo no of directories are $d [KRISHNASAI@localhost exp13]$ ls 14palendrom.sh 17fact.sh 3data.sh 4.sh kkk [KRISHNASAI@localhost exp13]$ sh 4.sh no of ordinary files are 4 no of directories are 1

bphanikrishna.wordpress.com FOSSLAB Page 4 of 38 CSE ([email protected] II-Sem) EXP-13

5. Write a shell script to check whether a given number is perfect or not

[KRISHNASAI@exp13]$ cat [KRISHNASAI@localhost exp13]$ cat 5perfect.sh 5perfecta.sh echo "Enter a number:" n=1 read n while [ $n -lt 500 ] i=1 do sum=0 i=1 while [ $i -lt $n ] sum=0 do while [ $i -lt $n ] if [ `expr $n % $i` -eq 0 ] do then if [ `expr $n % $i` -eq 0 ] sum=`expr $sum + $i` then fi sum=`expr $sum + $i` i=`expr $i + 1` fi done i=`expr $i + 1` if [ $sum -eq $n ] done then if [ $sum -eq $n ] echo "$n is a perfect number" then else echo "$n is a perfect number" echo "$n is not a perfect number" fi fi n=`expr $n + 1 ` done [KRISHNASAI@ exp13]$ sh [KRISHNASAI@exp13]$ sh 5perfecta.sh 5perfect.sh 6 is a perfect number Enter a number: 28 is a perfect number 6 496 is a perfect number 6 is a perfect number [KRISHNASAI@lexp13]$ sh 5perfect.sh Enter a number: 22 22 is not a perfect number

Description: A perfect number: a number is perfect when the sum of its divisors (except the number itself) equals the given number. Examples of perfect numbers 6 : The divisors of 6 are 1,2,3 & 6. To show that this is a perfect number we could all the divisors except the number itself 1+2+3 = 6 28: 1 + 2 + 4 + 7 + 14 =28 496 and 8128 are also perfect number.

bphanikrishna.wordpress.com FOSSLAB Page 5 of 38 CSE ([email protected] II-Sem) EXP-13 6. Write a menu driven shell script to copy, edit, rename and delete a file

[KRISHNASAI@localhost exp13]$ vi 6fop.sh ch=0 while [ $ch -ne 9 ] do clear echo "1.Display current dir" echo "2.Listing the dir" echo "3.Make a dir" echo "4.Copy a file" echo "5.Rename file" echo "6.Delete file" echo "7.Edit file" echo "8.open or display file" echo "9.Exit"

echo "Enter your choice" read ch case $ch in 1)echo "Current Dir is : " pwd;; 2)echo "Directories are" ls;; 3)echo "Enter dir name to create" read d mkdir $d echo $d" Dir is created";; 4)echo "Enter filename from copy" read f1 echo "Enter filenm2 to be copied" read f2 cp $f1 $f2 echo $f2" is copied from "$f1;; 5)echo "Enter file name to rename" read f1 echo "Enter new name of file" read f2 mv $f1 $f2 echo $f1" is renamed as "$f2;; 6)echo "Enter any filenm to be delete" read f1 rm $f1 echo $f1" is deleted";; 7)echo "Enter any file to be editing " read f1 vi $f1;; 8) echo "Enter the file name you want to open" read f1 cat $f1;; 9)echo "Have a nice time" exit;; *)echo "Invalid choice entered";;

bphanikrishna.wordpress.com FOSSLAB Page 6 of 38 CSE ([email protected] II-Sem) EXP-13 esac echo "are you continue (1 for yes / 0 for No)" read temp if [ $temp -eq 0 ] then ch=9 fi done

Output: [KRISHNASAI@localhost exp13]$sh 6fop.sh

1.Display current dir Enter your choice 2.Listing the dir 5 3.Make a dir Enter file name to rename 4.Copy a file kkkk 5.Rename file Enter new name of file 6.Delete file srisai 7.Edit file kkkk is renamed as srisai 8.open or display file 9.Exit Enter your choice Enter your choice 1 6 Current Dir is : Enter any filenm to be delete /home/KRISHNASAI/krishna/foss/exp13 h1 are you continue (1 for yes / 0 for No) h1 is deleted

Enter your choice Enter your choice 2 7 Directories are Enter any file to be editing 13delz.sh 15amga.sh Krish Enter your choice Enter your choice 3 8 Enter dir name to create Enter the file name you want to open srisai krish srisai Dir is created alway say i don't have fear are you continue (1 for yes / 0 for No) be a hero

bphanikrishna.wordpress.com FOSSLAB Page 7 of 38 CSE ([email protected] II-Sem) EXP-13

7. Write a shell script for concatenation of two strings Program: Output: [KRISHNASAI@exp13]$ cat 7concat.sh [KRISHNASAI@exp13]$ sh 7concat.sh echo Enter first string: Enter first string: read s1 krishna echo Enter second string: Enter second string: read s2 sai s3=$s1$s2 Concatinated string:- krishnasai len=${#s3} krishnasai length:- 10 echo Concatinated string:- $s3 echo $s3 length:- $len

8. Write a shell script which will display Fibonacci series up to a given number of argument. [KRISHNASAI@localhost exp13]$ cat [KRISHNASAI@localhost exp13]$ cat 8fib.sh 8fiba.sh echo enter the number of terms for n in $* read n do f1=0 f1=0 f2=1 f2=1 i=3 i=3 echo "fibonacci seroes up to $n numbers" echo "fibonacci seroes up to $n numbers" echo $f1 echo $f1 echo $f2 echo $f2 while [ $i -le $n ] while [ $i -le $n ] do do f3=`expr $f1 + $f2` f3=`expr $f1 + $f2` f1=$f2 f1=$f2 f2=$f3 f2=$f3 i=`expr $i + 1` i=`expr $i + 1` echo $f3 echo $f3 done done exit 0 done exit 0 [KRISHNASAI@localhost exp13]$ sh [KRISHNASAI@localhost exp13]$ sh 8fib.sh 8fiba.sh 4 enter the number of terms fibonacci seroes up to 4 numbers 9 0 fibonacci seroes up to 9 numbers 1 0 1 1 2 1 2 3 5 8 13 21 awk 'BEGIN {a=0;b=1; while(++x<=10){print a; t=a;a=a+b;b=t}; exit}'

bphanikrishna.wordpress.com FOSSLAB Page 8 of 38 CSE ([email protected] II-Sem) EXP-13 9. Write a shell script to accept student number, name, marks in 5 subjects. Find total, average and grade. Display the result of student and store in a file called stu.dat. Rules: avg>=80 then grade A Avg<60&&Avg>=50 then grade D Avg<80&&Avg>=70 then grade B Avg<50&&Avg>=40 then grade E Avg<70&&Avg>=60 then grade C Else grade F

[KRISHNASAI@localhost exp13]$ cat 9stum.sh echo "Enter Student name" read name echo "Enter Student Registered Number" read reg echo "Enter the marks of five subjects : " read m1 m2 m3 m4 m5 let total=$m1+$m2+$m3+$m4+$m5 let per=(total/5) echo Name :$name echo Registered number :$reg echo student total marks:$total echo Student percentage :$per if [ $per -ge 80 ] then echo gread :A elif [ $per -ge 70 -a $per -lt 80 ] then echo Gread :B elif [ $per -ge 60 -a $per -lt 70 ] then echo Gread :C elif [ $per -ge 50 -a $per -lt 60 ] then echo Gread :D elif [ $per -ge 40 ] && [ $per -lt 50 ] then echo Gread :E else echo "Gread :F(fail) " fi OUTPUT:- [KRISHNASAI@ exp13]$ sh 9stum.sh Name :krishnasai Enter Student name Registered number :11275715034 krishnasai student total marks:440 Enter Student Registered Number Student percentage :88 11275715034 gread :A Enter the marks of five subjects : 90 85 90 95 80

bphanikrishna.wordpress.com FOSSLAB Page 9 of 38 CSE ([email protected] II-Sem) EXP-13 10. Write a shell script to accept empno,empname,basic. Find DA,HRA,TA,PF using following rules. Display empno, empname, basic, DA,HRA,PF,TA,GROSS SAL and NETSAL. Also store all details in a file called emp.dat Rules: HRA is 18% of basic if basic > 5000 otherwise 550 DA is 35% of basic PF is 13% of basic IT is 14% of basic TA is 10% of basic Program: [KRISHNASAI@H exp13]$ vi 10salary.sh echo "Enter the EmployeeID (empno)" read empno echo "Enter the Name of Employee" read empname echo "enter the basic salary:" read bsal bsalp=`expr $bsal / 100` if [ $bsal -gt 5000 ] then hra=`expr $bsalp \* 18` else hra=550 fi da=`expr $bsalp \* 35` pf=`expr $bsalp \* 13` it=`expr $bsalp \* 14` ta=`expr $bsalp \* 10` gross=`expr $bsal + $hra + $da + $ta` netsal=`expr $gross - $pf - $it` echo "Empno : $empno"|tee emp.dat echo "Empname : $empname"|tee cat >> emp.dat echo "Basic : $bsal"|tee cat >> emp.dat echo "HRA(House Rent Allowance): $hra"|tee cat >> emp.dat echo "PF (Provident fund) : $pf"|tee cat >> emp.dat echo "TA (Travalling Allowance): $ta"|tee cat >> emp.dat echo "IT (Income Tax) : $it"|tee cat >> emp.dat echo "Gross salary : $gross"|tee cat >> emp.dat echo "netsalary : $netsal"|tee cat >>emp.dat Output: [KRISHNASAI@H exp13]$ sh 10salary.sh Enter the EmployeeID (empno) 1234 Enter the Name of Employee krishnasai enter the basic salary: 25000

bphanikrishna.wordpress.com FOSSLAB Page 10 of 38 CSE ([email protected] II-Sem) EXP-13 Empno : 1234 [KRISHNASAI@H exp13]$ cat emp.dat Empno : 1234 Empname : krishnasai Basic : 25000 HRA(House Rent Allowance): 4500 PF (Provident fund) : 3250 TA (Travalling Allowance): 2500 IT (Income Tax) : 3500 Gross salary : 40750 netsalary : 34000 TA = BASIC SAL*PERCENTAGE/100 DA= BASIC SAL*PERCENTAGE/100 HRA= BASIC SAL*PERCENTAGE/100 GROSS SAL =BASIC SAL+ TA + DA + HRA PF= GROSS SAL*PERCENTAGE/100 NET SAL = GROSS SAL -( PF + LIC+IT)

Gross Salary: is the amount of salary paid after adding all benefits and allowances and before deducting any tax

Net Salary: is what is left of your salary after deductions have been made. Take Home Salary: Is usually the Net Salary unless there are some personal deductions like loan or bond re-payments.

Cost to Company: Companies use the term “Cost to Company” to calculate the total cost to employ. I.e. all the costs associated with an employment contract. Major part of CTC comprises of compulsory deductibles. These include deductions for provident fund, medical insurance etc. They form a part of your compensation structure but you not get them as a part of in-hand salary. As such, although it increases your CTC, it does not increment your net salary.

bphanikrishna.wordpress.com FOSSLAB Page 11 of 38 CSE ([email protected] II-Sem) EXP-13

11. Write a shell script to demonstrate break and continue statements

Program: beak Program: continue [KRISHNASAI@Hexp13]$vi11break.sh [KRISHNASAI@Hexp13]$ vi 11continu.sh val="1 2 3 4 5 6 7 8 9 10" val="1 2 3 4 5 6 7 8 9 10" for num in $val for num in $val do do e=`expr $num % 2` e=`expr $num % 2` if [ $e -eq 0 ] if [ $e -eq 0 ] then then echo "$num Number is an even echo "$num Number is an even number!!" number!!" continue continue fi fi echo "$num is odd number" echo "$num is odd number" if [ $num -eq 5 ] done then break fi done

Output: Output: [KRISHNASAI@H exp13]$ sh 11break.sh [KRISHNASAI@Hexp13]$ sh 11continu.sh 1 is odd number 1 is odd number 2 Number is an even number!! 2 Number is an even number!! 3 is odd number 3 is odd number 4 Number is an even number!! 4 Number is an even number!! 5 is odd number 5 is odd number 6 Number is an even number!! 7 is odd number 8 Number is an even number!! 9 is odd number 10 Number is an even number!!

To stop a loop or skip iterations of the loop two statements used to control shell loops: 1. The break statement 2. The continue statement The infinite Loop: All the loops have a limited life and they come out once the condition is false or true depending on the loop. A loop may continue forever due to required condition is not met. A loop that executes forever without terminating executes an infinite number of times. For this reason, such loops are called infinite loops. Example:

bphanikrishna.wordpress.com FOSSLAB Page 12 of 38 CSE ([email protected] II-Sem) EXP-13 Here is a simple example that uses the while loop to display the numbers zero to nine: #!/bin/sh a=10 while [ $a -ge 10 ] do echo $a a=`expr $a + 1` done This loop would continue forever because a is alway greater than or equal to 10 and it would never become less than 10. So this true example of infinite loop. The break statement: The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. It then steps down to the code following the end of the loop. Syntax: The following break statement would be used to come out of a loop: break The break command can also be used to exit from a nested loop using this format: break n Here n specifies the nth enclosing loop to exit from. Example: Here is a simple example which shows that loop would terminate as soon as a becomes 5: #!/bin/sh a=0 while [ $a -lt 10 ] do echo $a if [ $a -eq 5 ] then break fi a=`expr $a + 1` done This will produce following result: 0 1 2 3 4 5 Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals 2 and var2 equals 0: #!/bin/sh

for var1 in 1 2 3 do for var2 in 0 5 do

bphanikrishna.wordpress.com FOSSLAB Page 13 of 38 CSE ([email protected] II-Sem) EXP-13 if [ $var1 -eq 2 -a $var2 -eq 0 ] then break 2 else echo "$var1 $var2" fi done done This will produce following result. In the inner loop, you have a break command with the argument 2. This indicates that if a condition is met you should break out of outer loop and ultimately from inner loop as well. 1 0 1 5 The continue statement: The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop. This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop. Syntax: continue Like with the break statement, an integer argument can be given to the continue command to skip commands from nested loops. continue n Here n specifies the nth enclosing loop to continue from.

bphanikrishna.wordpress.com FOSSLAB Page 14 of 38 CSE ([email protected] II-Sem) EXP-13

12. Write a shell script to satisfy the following menu options a) Display current directory path b) Display todays date c) Display users who are connected to the unix system d) Quit

[KrishnaSAI@H exp13]$ vi 12someactions.sh ch=0 while [ $ch -ne 4 ] do clear echo "1.Display current dir" echo "2.Display Today date" echo "3.Display users who are connected to the unix system" echo "4.Exit" echo "Enter your choice" read ch case $ch in 1)echo "Current Dir is : " pwd;; 2)echo "Today date is" today=$(date +"%A") tday=$(date +"%d-%B-%Y") time=$(date +"%r ||%z ") echo "Today is :$today" echo "Today date is :$tday" echo "Time :$time";; 3)echo " Users who are connected to shell " who>userlist i=0 for u in `who|cut -d" " -f1` do i=`expr $i + 1` done echo "Total number of users are : $i " echo "login user details in `date +"%D %H-%M-%S "`" echo "------" who|cut -d" " -f1 echo "------" ;; 4)echo "Have a nice time" exit;; *)echo "Invalid choice entered";; esac echo "are you continue (1 for yes / 0 for No)"

bphanikrishna.wordpress.com FOSSLAB Page 15 of 38 CSE ([email protected] II-Sem) EXP-13 read temp if [ $temp -eq 0 ] then ch=4 fi done

Output: 1.Display current dir Enter your choice 2.Display Today date 2 3.Display users who are connected to the unix Today date is system Today is :Thursday 4.Exit Today date is :12-March-2015 Enter your choice Time :04:28:04 PM ||+0530 1 are you continue (1 for yes / 0 for No) Current Dir is : /home/CSESTAFF/krishna/foss/exp13 are you continue (1 for yes / 0 for No) Enter your choice Enter your choice 3 4 Users who are connected to shell Have a nice time Total number of users are : 3 login user details in 03/12/15 16-28-23 ------CSESTAFF CSESTAFF CSESTAFF ------are you continue (1 for yes / 0 for No)

bphanikrishna.wordpress.com FOSSLAB Page 16 of 38 CSE ([email protected] II-Sem) EXP-13

13. Write a shell script to delete all files whose size is zero bytes from current directory

Program: [KRISHNASAI@localhost exp13]$ cat 13delempa.sh echo "Your present working directory is" echo `pwd` echo "FIles whose size is zero bytes are" echo "------" echo " `find . -type f -empty|cut -d"/" -f2` " echo "------" for i in `find . -type f -empty|cut -d"/" -f2` do echo "do you want to remove the {[ $i ]} file form this folder ( Press Y for yes, else N) " read de if [ "$de" == "y" ] then rm $i echo $i removed fi done if [ "$i" == "" ] then echo "In `pwd` there are no empty files" fi Output: Your present working directory is /home/KRISHNASAI/krishna/foss/exp13 FIles whose size is zero bytes are ------hhhhh hhhhh2 hhhhh1 hh ------do you want to remove the {[ hhhhh ]} file form this folder ( Press Y for yes, else N) y hhhhh removed do you want to remove the {[ hhhhh2 ]} file form this folder ( Press Y for yes, else N) n find -type f -size 0 -ls

bphanikrishna.wordpress.com FOSSLAB Page 17 of 38 CSE ([email protected] II-Sem) EXP-13 14. Write a shell script to display string palindrome from given arguments

for n in $* do s=`echo $n | wc -c` while [ $s -gt 0 ] do temp=`echo $n | cut -c $s` s=`expr $s - 1` temp1="$temp1$temp" done echo "Reverse string of # $n # is $temp1" if [ $n != $temp1 ] then echo "$n is not palandrome" else echo "$n is palandrome"

fi temp1="" done Output: [KRISHNASAI@localhost exp13]$ sh 14palindrome.sh malayalam 451 Reverse string of # malayalam # is malayalam malayalam is palandrome Reverse string of # 451 # is 154 451 is not palandrome

bphanikrishna.wordpress.com FOSSLAB Page 18 of 38 CSE ([email protected] II-Sem) EXP-13

15. Write a shell script which will display Armstrong numbers from given given arguments.

[KRISHNASAI@localhost exp13]$ vi [KRISHNASAI@localhost exp13]$ vi 15amg.sh 15amga.sh echo "Enter a number: " for c in $* read c do x=$c x=$c sum=0 sum=0 r=0 r=0 n=0 n=0 while [ $x -gt 0 ] while [ $x -gt 0 ] do do r=`expr $x % 10` r=`expr $x % 10` n=`expr $r \* $r \* $r` n=`expr $r \* $r \* $r` sum=`expr $sum + $n` sum=`expr $sum + $n` x=`expr $x / 10` x=`expr $x / 10` done done if [ $sum -eq $c ] then if [ $sum -eq $c ] echo "It is an Armstrong Number." then else echo " $c is an Armstrong Number." echo "It is not an Armstrong Number." else fi echo " $c is not an Armstrong Number." fi done [KRISHNASAI@localhost exp13]$ sh [KRISHNASAI@localhost exp13]$ sh 15amg.sh 15amga.sh 143 153 125 Enter a number: 143 is not an Armstrong Number. 143 153 is an Armstrong Number. It is not an Armstrong Number. 125 is not an Armstrong Number. [KRISHNASAIS@localhost exp13]$ sh 15amg.sh Enter a number: 153 It is an Armstrong Number.

bphanikrishna.wordpress.com FOSSLAB Page 19 of 38 CSE ([email protected] II-Sem) EXP-13

16. Write a shell script to display reverse numbers from given argument list

[KRISHNASAI@ exp13]$ vi 16res.sh [KRISHNASAIS@exp13]$ cat for n in $* 16resaa.sh do for n in $* s=`echo $n | wc -c` do while [ $s -gt 0 ] s=0 do m=$n temp=`echo $n | cut -c $s` while [ $n -gt 0 ] s=`expr $s - 1` do temp1="$temp1$temp" r=`expr $n % 10` done s=`expr $s \* 10 + $r` echo "Reverse string of # $n # is $temp1" n=`expr $n / 10` temp1="" done done echo "Reverse of $m is" $s done Output: [KRISHNASAI@exp13]$sh 16resaa.sh [KRISHNASAI@ exp13]$ sh 16res.sh 987 890 121 krishnasai 143 Reverse of 987 is 789 Reverse string of # krishnasai # is Reverse of 890 is 98 iasanhsirk Reverse of 121 is 121 Reverse string of # 143 # is 341

17. Write a shell script to display factorial value from given argument list

Program: [KRISHNASAI@localhost exp13]$ vi 17fact.sh i=1 f=1 echo " Enter the number" read n while [ $i -le $n ] do f=`expr $f \* $i` i=`expr $i + 1` done echo FACTORIAL of a given number $n is: $f [KRISHNASAI@localhost exp13]$ Output: [KRISHNASAI@localhost exp13]$ sh 17fact.sh Enter the number 5 FACTORIAL of a given number 5 is: 120 [KRISHNASAI@localhost exp13]$ sh 17fact.sh Enter the number 3 FACTORIAL of a given number 3 is: 6

bphanikrishna.wordpress.com FOSSLAB Page 20 of 38 CSE ([email protected] II-Sem) EXP-13

18. Write a shell script which will find maximum file size in the given argument list

Program: [KRISHNASAI@H exp13]$ cat maxsize.sh max=0 for k in $* do for i in `ls -l $k|tr -s " "|cut -f 5 -d " "` do if [ $max -le $i ] then max=$i f=$k fi done done echo maximum size file name is : $f echo $f size is :$max

Output: [KRISHNASAI@H exp13]$ sh maxsize.sh kkw lik sss maximum size file name is : sss sss size is :59

Verification: [KRISHNASAI@H exp13]$ wc kkw 4 9 47 kkw [KRISHNASAI@H exp13]$ wc lik 0 0 0 lik [KRISHNASAI@H exp13]$ wc sss 1 5 59 sss [KRISHNASAI@H exp13]$

bphanikrishna.wordpress.com FOSSLAB Page 21 of 38 CSE ([email protected] II-Sem) EXP-13

19. Write a shell script which will greet you “Good Morning”, ”Good Afternoon”, “Good Evening’ and “Good Night” according to current time. [KRISHNASAI@localhost exp13]$ cat 19time.sh hournow=`date | cut -c 12-13` user=`echo $HOME|cut -d"/" -f3` 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 Output: [KRISHNASAI@localhost exp13]$ sh 19time.sh .Good Evening Mr/Ms :KRISHNASAI.

bphanikrishna.wordpress.com FOSSLAB Page 22 of 38 CSE ([email protected] II-Sem) EXP-13

20. Write a shell script to sort the elements in a array using bubble sort technique

Program: [KRISHNASAI@localhost exp13]$ cat 20bubblea.sh echo "enter maximum number" read n # taking input from user echo "enter Numbers in array:" for (( i = 0; i < $n; i++ )) do read nos[$i] done #printing the number before sorting echo "Numbers in an array are:" for (( i = 0; i < $n; i++ )) do echo ${nos[$i]} done # Now do the Sorting of numbers for (( i = 0; i < ( $n - 1 ) ; i++ )) do for (( j = 0; j < ( $n - $i - 1); j++ )) do h=`expr $j + 1` if [ ${nos[$j]} -gt ${nos[ $h]} ]; then t=${nos[$j]} nos[$j]=${nos[$h]} nos[$h]=$t fi done done # Printing the sorted number echo -e "\n Sorted Numbers " for (( i=0; i < $n; i++ )) do echo ${nos[$i]} done Output: [KRISHNASAI@localhost exp13]$ sh 20bubblea.sh enter maximum number 5 enter Numbers in array: 8 -1 -0 8 6 Numbers in an array are: 8 -1 -0 8

bphanikrishna.wordpress.com FOSSLAB Page 23 of 38 CSE ([email protected] II-Sem) EXP-13 6

Sorted Numbers -1 -0 6 8 8 Description: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Step-by-step example Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required. First Pass: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass: ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass: ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 )

bphanikrishna.wordpress.com FOSSLAB Page 24 of 38 CSE ([email protected] II-Sem) EXP-13 21. Write a shell script to find largest element in a array

Program: [krishnasai@dnrcet ~]$ vi 21bignum.sh echo "enter maximum number" read n # taking input from user echo "enter Numbers in array:" for (( i = 0; i < $n; i++ )) do read nos[$i] done #Finding largest number in given array echo "Numbers in an array are:" for (( i = 0; i < $n; i++ )) do echo ${nos[$i]} done res=${nos[1]} for (( i=1; i < $n; i++)) do if [ $res -le ${nos[$i]} ] then res=${nos[$i]} fi done echo "Maximum element among the given $n elements is" echo "$res" Output: [krishnasai@dnrcet ~]$ sh 21bignum.sh enter maximum number 5 enter Numbers in array: 6 9 15 6 19 Numbers in an array are: 6 9 15 6 19 Maximum element among the given 5 elements is 19 [krishnasai@dnrcet ~]$

bphanikrishna.wordpress.com FOSSLAB Page 25 of 38 CSE ([email protected] II-Sem) EXP-13

22. Write an awk program to print sum, avg of students marks list

[KrishnaSAI@H exp13]$ cat avg1.awk Output: # Begin [KrishnaSAI@H exp13]$ awk -f BEGIN { avg1.awk students tot=0; } there are 4 students, their average is: # Dev { Name :krishna name[NR]=$1; Total:230 total[NR]=($2 + $3 + $4) Average: 76.67 average[NR]=total[NR]/ 3; Name :ravi tot=tot + 1; Total:240 } Average: 80.00 # End Name :pushpa END { Total:225 print "there are "tot" students, their average Average: 75.00 is:\n"; Name :lakshmi i = 1; Total:205 while (i <= tot){ Average: 68.33 printf("Name :%-10s \n Total:%d \n Average: [KrishnaSAI@H exp13]$ %.2f \n", name[i] ,total[i], ave rage[i++]); } } [KrishnaSAI@H exp13]$ cat students krishna 75 75 80 ravi 70 80 90 pushpa 80 90 55 lakshmi 60 78 67 [KrishnaSAI@H exp13]$

bphanikrishna.wordpress.com FOSSLAB Page 26 of 38 CSE ([email protected] II-Sem) EXP-13

23. Write an awk program to display students pass/fail report

[KrishnaSAI@H exp13]$ cat pf.awk [KrishnaSAI@H exp13]$ cat # Begin studdata BEGIN { Krishna 75 80 95 tot=0; Ravi 85 94 79 } Pushpa 90 90 90 Lakshmi 80 80 80 # Dev rama 30 35 35 { if($2>=35 && $3>=35 && $4>=35) { status[NR]="Pass" } else{ status[NR]="fail" } name[NR]=$1; total[NR]=($2 + $3 + $4) average[NR]=total[NR]/ 3; tot=tot + 1; } # End END { print "there are "tot" students, their average is:\n"; i = 1; printf("Name\tTotalMarks\tAverage\tStatus\n"); while (i <= tot){

printf("%s\t\t%d\t%.2f\t%s\n", name[i] ,total[i], average[i], status[i]); i++; } } [KrishnaSAI@H exp13]$ awk -f pf.awk studdata there are 5 students, their average is:

Name TotalMarks Average Status Krishna 250 83.33 Pass Ravi 258 86.00 Pass Pushpa 270 90.00 Pass Lakshmi 240 80.00 Pass rama 100 33.33 fail [KrishnaSAI@H exp13]$

bphanikrishna.wordpress.com FOSSLAB Page 27 of 38 CSE ([email protected] II-Sem) EXP-13

24. Write an awk program to count the no. of vowels in a given file

Program: [KRISHNASAI@H exp13]$ cat ffawk.awk BEGIN { FS = " "; # Space separates words line_count = 0; # Number of lines word_count = 0; # Number of words char_count = 0 # Number of characters vowel=0; cons=0; spe=0; num=0; } { line_count++; # Count the next line word_count += NF; # Word count in line = NF char_count += length($0) + 1 # Len of line + 1 newline } { split($0, chars, "") for (i=1; i <= length($0); i++) { tmp1=match(chars[i],/[AaEeIiOoUu]/) if(tmp1) vowel++;

tmp2=match(chars[i],/[BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz]/) if(tmp2) cons++;

tmp3=match(chars[i],/[0-9]/) if(tmp3) num++;

if(!tmp1 && !tmp2 && !tmp3) spe++;

} }

!/[aA]|[eE]|[Ii]|[Oo]|[Uu]/{ k++ } /[aA]|[eE]|[Ii]|[Oo]|[Uu]/{ v++ }

bphanikrishna.wordpress.com FOSSLAB Page 28 of 38 CSE ([email protected] II-Sem) EXP-13 END { printf "Number of lines = %d\n", line_count printf "Number of words = %d\n", word_count printf "Number of characters = %d\n", char_count printf "No of lines not contain vowel = %d \n",k printf "No of lines contain vowel = %d \n",v printf "Number of vowels in a given file = %d \n",vowel printf "Number of consonents in a given file= %d \n", cons printf "Number of Numerical data [0-9] in a given file = %d \n",num printf "Number of specail characters = %d \n",spe }

[KRISHNASAI@H exp13]$ cat kkw hi how are you tell me my dry 345 %$9

Output:

[KRISHNASAI@H exp13]$ awk -f ffawk.awk kkw Number of lines = 6 Number of words = 10 Number of characters = 39 No of lines not contain vowel = 4 No of lines contain vowel = 2 Number of vowels in a given file = 8 Number of consonents in a given file= 14 Number of Numerical data [0-9] in a given file = 4 Number of specail characters = 7 [KRISHNASAI@H exp13]$

bphanikrishna.wordpress.com FOSSLAB Page 29 of 38 CSE ([email protected] II-Sem) EXP-13 25. Write an awk program which will find maximum word and its length in the given input File

[KrishnaSAI@H awk]$ cat wcs.awk Begin { lineCount=1 maxi=0; } # start line count at 1 { { c=split($0, s); for(n=1; n<=c; ++n) { wor=s[n] len=length(s[n]) if(maxi<=len) { maxi=len w=wor } print(wor,len) } } $1 printf("maximum size of the word in the abouve line is :"); print(w,maxi) } Output: [KrishnaSAI@H awk]$ cat f Without doing work nothing is yours it better to die with memories then to live only in dream ok [KrishnaSAI@H awk]$ awk -f wcs.awk f Without 7 doing 5 work 4 nothing 7 is 2 yours 5 maximum size of the word in the abouve line is :nothing 7 it 2 better 6 to 2 die 3 with 4 memories 8 then 4 to 2 live 4 only 4 in 2 dream 5 maximum size of the word in the abouve line is :memories 8 ok 2 maximum size of the word in the abouve line is :memories 8 [KrishnaSAI@H awk]$

bphanikrishna.wordpress.com FOSSLAB Page 30 of 38 CSE ([email protected] II-Sem) EXP-13

26. Write a shell script to generate the mathematical tables.

[KRISHNASAI@localhost exp13]$ cat 26mt.sh echo "Enter a number:" read n echo "enter a table range" read r echo "Multiplication table of $n is:" for (( i=1; i<=$r; i++ )) do result=$[ $n * $i ] echo $n "*" $i = $result done Output: [KRISHNASAI@localhost exp13]$ sh 26mt.sh Enter a number: 3 enter a table range 3 Multiplication table of 3 is: 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9

bphanikrishna.wordpress.com FOSSLAB Page 31 of 38 CSE ([email protected] II-Sem) EXP-13

27. Write a shell script to sort elements of given array by using selection sort.

Program: Output: [KSAI@Hexp13]$ vi 27selectionsort.sh [KSAI@Hexp13]$ sh 27selectionsort.sh echo "Enter size of an aray" Enter size of an aray read n 5 # taking input from user enter elements in array: echo "enter elements in array:" 9 for (( i = 0; i < $n; i++ )) 1 do 5 read arr[$i] 1 done 6 #printing the number before sorting Numbers in an array are: echo "Numbers in an array are:" 9 for (( i = 0; i < $n; i++ )) 1 do 5 echo ${arr[$i]} 1 done 6 # selection sorting operations after SELECTION SORT for (( i = 0; i < ( $n - 1 ) ; i++ )) 1 do 1 min=${arr[$i]} 5 index=$i 6 for (( j = i+1; j < $n; j++ )) 9 do [KSAI@Hexp13]$ if [ ${arr[$j]} -lt $min ] then min=${arr[$j]} index=$j fi done t=${arr[$i]} arr[$i]=${arr[$index]} arr[$index]=$t done # Printing the sorted number echo "\n after SELECTION SORT " for (( i=0; i < $n; i++ )) do echo ${arr[$i]} done

bphanikrishna.wordpress.com FOSSLAB Page 32 of 38 CSE ([email protected] II-Sem) EXP-13

28. Write a shell script to search given number using binary search.

Program: [krishnasai@localhost ~]$ vi 28binarysearch.sh echo "enter maximum number" read n # taking input from user echo "enter Numbers in array:" for (( i = 0; i < $n; i++ )) do read nos[$i] done #printing the number before sorting echo "Numbers in an array are:" for (( i = 0; i < $n; i++ )) do echo ${nos[$i]} done #find element echo "Enter the key element whom you want to search in given $n elements" read key low=0 high=`expr $n - 1` count=0 while [ $count -eq 0 -a $high -ge $low ] do m=`expr $low + $high` mid=`expr $m / 2` if [ $key -eq ${nos[$mid]} ] then count=1 elif [ $key -gt ${nos[$mid]} ] then low=`expr $mid + 1` else high=`expr $mid - 1` fi done if [ $count -eq 1 ] then echo "the given key { $key }is found at { $mid } position" else echo "given key $key is not found" fi

bphanikrishna.wordpress.com FOSSLAB Page 33 of 38 CSE ([email protected] II-Sem) EXP-13 Output: [krishnasai@localhost ~]$ sh 28buublesort.sh enter maximum number 5 enter Numbers in array: 7 8 9 14 19 Numbers in an array are: 7 8 9 14 19 Enter the key element whom you want to search in given 5 elements 9 the given key { 9 }is found at { 2 } position

bphanikrishna.wordpress.com FOSSLAB Page 34 of 38 CSE ([email protected] II-Sem) EXP-13

29. Write a shell script to find number of vowels, consonants, numbers, white spaces and special characters in a given string.

[KRISHNASAI@localhost exp13]$ cat 29countvcs.sh clear echo "Type any String" read string length=`echo $string|wc -c` nvowels=0 nconsonants=0 ndigits=0 nsymbols=0 leng=`expr $length - 1`; while [ $length -gt 1 ] do length=`expr $length - 1` h=`echo $string | cut -c $length` case $h in [AaEeIiOoUu]) nvowels=`expr $nvowels + 1` ;; [BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz]) nconsonants=`expr $nconsonants + 1` ;; [0-9]) ndigits=`expr $ndigits + 1` ;; *) nsymbols=`expr $nsymbols + 1` esac done echo "String is : $string" echo "Length of given string: $leng" echo "Number of Vowels : $nvowels" echo "Number of Consonants : $nconsonants" echo "Number of Digits : $ndigits" echo "Number of special char: $nsymbols" [KRISHNASAI@localhost exp13]$ OUTPUT: [KRISHNASAI@localhost exp13]$ sh 29countvcs.sh Type any String Krishnasai4all $KRISHNASAI$ String is : Krishnasai4all $KRISHNASAI$ Length of given string: 20 Number of Vowels : 6 Number of Consonants : 10 Number of Digits : 1 Number of special char: 3

bphanikrishna.wordpress.com FOSSLAB Page 35 of 38 CSE ([email protected] II-Sem) EXP-13

30. Write a shell script to lock the terminal.

Program: [KRISHNASAI@localhost exp13]$ vi 30terminal.sh clear stty -echo echo "enter password to lock the terminal" read pass1 echo " Re-enter password" read pass2 if [ "$pass1" = "$pass2" ] then echo "system is locked" echo "enter password to unlock" trap ``/1 2 3 9 15 18 while true do read pass3 if [ $pass1 = $pass3 ] then echo "system unlocked" stty echo exit else echo "password mismatch" fi done else echo "password mismatch" stty echo fi [KRISHNASAI@localhost exp13]$ Output: [KRISHNASAI@localhost exp13]$ sh 30terminal.sh enter password to lock the terminal Re-enter password system is locked enter password to unlock password mismatch system unlocked Description: What is a Terminal ? A real terminal consists of a screen and keyboard that one uses to communicate remotely with a (host) computer. One uses it just like it was a personal computer but the terminal is remote from its host computer (on the other side of the room or even on the other side of the world). Programs execute on the host computer but the results display on the terminal screen.

bphanikrishna.wordpress.com FOSSLAB Page 36 of 38 CSE ([email protected] II-Sem) EXP-13

The terminal's computational ability is relatively low (otherwise it would be a computer and not a terminal). The terminal is generally limited to the ability to display what is sent to it (possibly including full-screen graphics) and the ability to send to the host what is typed at the keyboard. A text-terminal only displays text on the screen without pictures. In the days of mainframes from the mid 1970's to the mid 1980's, most people used real text-terminals to communicate with computers. They typed in programs, ran programs, wrote documents, issued printing commands, etc. A cable connected the terminal to the computer (often indirectly). It was called a terminal since it was located at the terminal end of this cable. Some text-terminals were called "graphic" but the resolution was poor and the speed slow by today's standards due to the high cost of memory and the limited speed of the conventional , etc. Today, real terminals are not as common as they once were and most people that use terminals use a personal computer to emulate a terminal. Almost everyone who uses Linux uses terminal emulation. Without X Window, one uses a text interface (virtual terminal). It's also called a command line interface. In X Window one can get one or more terminal windows (, , or zterm). All these use software to emulate a real terminal. Setty: stty changes and prints terminal line settings Syntax stty [-F DEVICE | --file=DEVICE] [SETTING]... stty [-F DEVICE | --file=DEVICE] [-a|--all] stty [-F DEVICE | --file=DEVICE] [-g|--save] Description stty displays or changes the characteristics of the terminal.

Examples stty sane Reset all terminal settings to "sane" values; this has the effect of "fixing" the terminal when another program alters the terminal settings to an unusable condition. stty -echo Disable echoing of terminal input. stty echo Re-enable echoing of terminal input. stty -a Display all current terminal settings.

Trapping Signals: When you press the Ctrl+C or Break key at your terminal during execution of a shell program, normally that program is immediately terminated, and your command prompt returned. This may not always be desirable. For instance, you may end up leaving a bunch of temporary files that won't get cleaned up. Trapping these signals is quite easy, and the trap command has the following syntax: $ trap commands signals

bphanikrishna.wordpress.com FOSSLAB Page 37 of 38 CSE ([email protected] II-Sem) EXP-13 Here command can be any valid Unix command, or even a user-defined function, and signal can be a list of any number of signals you want to trap. There are three common uses for trap in shell scripts: 1. Clean up temporary files 2. Ignore signals Cleaning Up Temporary Files: As an example of the trap command, the following shows how you can remove some files and then exit if someone tries to abort the program from the terminal: $ trap "rm -f $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 2 From the point in the shell program that this trap is executed, the two files work1$$ and dataout$$ will be automatically removed if signal number 2 is received by the program. So if the user interrupts execution of the program after this trap is executed, you can be assured that these two files will be cleaned up. The exit command that follows the rm is necessary because without it execution would continue in the program at the point that it left off when the signal was received. Signal number 1 is generated for hangup: Either someone intentionally hangs up the line or the line gets accidentally disconnected. You can modify the preceding trap to also remove the two specified files in this case by adding signal number 1 to the list of signals: $ trap "rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 1 2 Now these files will be removed if the line gets hung up or if the Ctrl+C key gets pressed. The commands specified to trap must be enclosed in quotes if they contain more than one command. Also note that the shell scans the command line at the time that the trap command gets executed and also again when one of the listed signals is received. So in the preceding example, the value of WORKDIR and $$ will be substituted at the time that the trap command is executed. If you wanted this substitution to occur at the time that either signal 1 or 2 was received you can put the commands inside single quotes: $ trap 'rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit' 1 2

bphanikrishna.wordpress.com FOSSLAB Page 38 of 38