CSE ([email protected] II-Sem) EXP-13
Page 1 of 38bphanikrishna.wordpress.comFOSSLAB
1. Write a shell script to check whether a particular user has logged in or not. If he haslogged in, also check whether he has eligibility to receive a message or not.
[KRISHNASAI@localhost exp13]$ vi 1check.shfunction checkuser{f=0;echo "----------------------------------"
for u in `who | cut -f1 -d" " | sort | uniq`do
who>userlistif [ $u = $1 ]
thenecho "$1 is available"echo "$1 is logged in " `grep -c $1 userlist` " terminals "echo "$1 is logged at"grep "$1" userlist|cut -d"(" -f2f=`expr $f + 1`fidoneif [ $f -lt 1 ]thenecho "user not available"fi}if [ -z $1 ]then
echo "Enter username: "read kcheckuser $k
echo "----------------------------------"exit 1
ficheckuser $1exit 1
Output:[KRISHNASAI@exp13]$ sh 1check.shEnter username:KRISHNASAI----------------------------------KRISHNASAI is availableKRISHNASAI is logged in 1 terminalsKRISHNASAI is logged at192.168.1.191)----------------------------------
[KRISHNASAI@exp13]$ sh 1check.shEnter username:krishna----------------------------------krishna is availablekrishna is logged in 2 terminalskrishna is logged at192.168.1.166)192.168.1.118)----------------------------------
CSE ([email protected] II-Sem) EXP-13
Page 2 of 38bphanikrishna.wordpress.comFOSSLAB
2. Write a shell script to accept the name of the file from standard input and perform thefollowing tests on it
a) File executableb) File readablec) File writabled) Both readable & writable
[krishnasai@exp13]$ vi 2fp.shecho enter a file nameread fileif [ -e $file ]then
echo "$file exists"if [ -f $file ]then
echo "$file is an ordinary file"if [ -r $file ]then
echo "$file has read access"else
echo "$file does not have read access"fiif [ -w $file ]then
echo "$file has write permission"else
echo "$file does not have write permission"fiif [ -x $file ]then
echo "$file has execute permission"else
echo "$file does not have execute permission"fiif [ -r $file ] && [ -w $file ]thenecho "$file has both read and write operations"fielif [ -d $file ]then
echo "$file is a directory"fielse
echo "$file does not exist"fi
Output:
[krishnasai@exp13]$sh 2fp.shenter a file nameh1h1 existsh1 is an ordinary fileh1 does not have read accessh1 has write permissionh1 has execute permission
CSE ([email protected] II-Sem) EXP-13
Page 3 of 38bphanikrishna.wordpress.comFOSSLAB
3. Write a shell script which will display the username and terminal name who loginrecently in to the unix system
[KRISHNASAI@Host exp13]$ vi 3.ut.shtoday=$(date +"%A")tday=$(date +"%d-%B-%Y")time=$(date +"%r ||%z ")echo "Today is :$today"echo "Today date is :$tday"echo "Time :$time"who>userlisti=0for u in `who|cut -d" " -f1`doi=`expr $i + 1`doneecho "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>uwho|cut -d"(" -f2>tpaste u techo "---------------------------------"
[KRISHNASAI@Host exp13]$ sh 3.ut.shToday is :TuesdayToday date is :10-March-2015Time :05:58:18 PM ||+0530Total number of users are : 2login user details in 03/10/15 17-58-18---------------------------------USER TERMINAL=================================CSESTAFF 192.168.1.219)149P1A0521 192.168.1.118)---------------------------------
Syntaxdate +"%FORMAT"$ date +"%m-%d-%y"Sample output:
02-27-07
Time onlyType the followingcommand:
$ date +"%T"
Outputs:
19:55:04
CSE ([email protected] II-Sem) EXP-13
Page 4 of 38bphanikrishna.wordpress.comFOSSLAB
4. Write a shell script to find no. of files in a directory
[KRISHNASAI@localhost exp13]$ vi 4.shf=0d=0for i in `ls -l|cut -c 1`doif [ $i = "-" ]thenf=`expr $f + 1`elif [ $i = "d" ]thend=`expr $d + 1`fidoneecho no of ordinary files are $fecho no of directories are $d[KRISHNASAI@localhost exp13]$ ls14palendrom.sh 17fact.sh 3data.sh 4.sh kkk[KRISHNASAI@localhost exp13]$ sh 4.shno of ordinary files are 4no of directories are 1
CSE ([email protected] II-Sem) EXP-13
Page 5 of 38bphanikrishna.wordpress.comFOSSLAB
5. Write a shell script to check whether a given number is perfect or not
[KRISHNASAI@exp13]$ cat5perfect.shecho "Enter a number:"read ni=1sum=0while [ $i -lt $n ]doif [ `expr $n % $i` -eq 0 ]thensum=`expr $sum + $i`fii=`expr $i + 1`doneif [ $sum -eq $n ]thenecho "$n is a perfect number"elseecho "$n is not a perfect number"fi
[KRISHNASAI@localhost exp13]$ cat5perfecta.shn=1while [ $n -lt 500 ]doi=1sum=0while [ $i -lt $n ]doif [ `expr $n % $i` -eq 0 ]thensum=`expr $sum + $i`fii=`expr $i + 1`doneif [ $sum -eq $n ]thenecho "$n is a perfect number"fin=`expr $n + 1 `done
[KRISHNASAI@ exp13]$ sh5perfect.shEnter a number:66 is a perfect number[KRISHNASAI@lexp13]$ sh5perfect.shEnter a number:2222 is not a perfect number
[KRISHNASAI@exp13]$ sh 5perfecta.sh6 is a perfect number28 is a perfect number496 is a perfect number
Description:A perfect number: a number is perfect when the sum of its divisors (except thenumber itself) equals the given number.Examples of perfect numbers6 : The divisors of 6 are 1,2,3 & 6. To show that this is a perfect number we could allthe divisors except the number itself1+2+3 = 628:1 + 2 + 4 + 7 + 14 =28496 and 8128 are also perfect number.
CSE ([email protected] II-Sem) EXP-13
Page 6 of 38bphanikrishna.wordpress.comFOSSLAB
6. Write a menu driven shell script to copy, edit, rename and delete a file
[KRISHNASAI@localhost exp13]$ vi 6fop.shch=0while [ $ch -ne 9 ]doclearecho "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 chcase $ch in1)echo "Current Dir is : "pwd;;2)echo "Directories are"ls;;3)echo "Enter dir name to create"read dmkdir $decho $d" Dir is created";;4)echo "Enter filename from copy"read f1echo "Enter filenm2 to be copied"read f2cp $f1 $f2echo $f2" is copied from "$f1;;5)echo "Enter file name to rename"read f1echo "Enter new name of file"read f2mv $f1 $f2echo $f1" is renamed as "$f2;;6)echo "Enter any filenm to be delete"read f1rm $f1echo $f1" is deleted";;7)echo "Enter any file to be editing "read f1vi $f1;;8) echo "Enter the file name you want to open"read f1cat $f1;;9)echo "Have a nice time"exit;;*)echo "Invalid choice entered";;
CSE ([email protected] II-Sem) EXP-13
Page 7 of 38bphanikrishna.wordpress.comFOSSLAB
esacecho "are you continue (1 for yes / 0 for No)"read tempif [ $temp -eq 0 ]thench=9fidone
Output:[KRISHNASAI@localhost exp13]$sh 6fop.sh
1.Display current dir2.Listing the dir3.Make a dir4.Copy a file5.Rename file6.Delete file7.Edit file8.open or display file9.Exit
Enter your choice5Enter file name to renamekkkkEnter new name of filesrisaikkkk is renamed as srisai
Enter your choice1Current Dir is :/home/KRISHNASAI/krishna/foss/exp13are you continue (1 for yes / 0 for No)
Enter your choice6Enter any filenm to be deleteh1h1 is deleted
Enter your choice2Directories are13delz.sh 15amga.sh
Enter your choice7Enter any file to be editingKrish
Enter your choice3Enter dir name to createsrisaisrisai Dir is createdare you continue (1 for yes / 0 for No)
Enter your choice8Enter the file name you want to openkrishalway say i don't have fearbe a hero
CSE ([email protected] II-Sem) EXP-13
Page 8 of 38bphanikrishna.wordpress.comFOSSLAB
7. Write a shell script for concatenation of two stringsProgram:[KRISHNASAI@exp13]$ cat 7concat.shecho Enter first string:read s1echo Enter second string:read s2s3=$s1$s2len=${#s3}echo Concatinated string:- $s3echo $s3 length:- $len
Output:[KRISHNASAI@exp13]$ sh 7concat.shEnter first string:krishnaEnter second string:saiConcatinated string:- krishnasaikrishnasai length:- 10
8. Write a shell script which will display Fibonacci series up to a given number ofargument.[KRISHNASAI@localhost exp13]$ cat8fib.shecho enter the number of termsread nf1=0f2=1i=3echo "fibonacci seroes up to $n numbers"echo $f1echo $f2while [ $i -le $n ]dof3=`expr $f1 + $f2`f1=$f2f2=$f3i=`expr $i + 1`echo $f3doneexit 0
[KRISHNASAI@localhost exp13]$ cat8fiba.shfor n in $*dof1=0f2=1i=3echo "fibonacci seroes up to $n numbers"echo $f1echo $f2while [ $i -le $n ]dof3=`expr $f1 + $f2`f1=$f2f2=$f3i=`expr $i + 1`echo $f3donedoneexit 0
[KRISHNASAI@localhost exp13]$ sh8fib.shenter the number of terms9fibonacci seroes up to 9 numbers01123581321
[KRISHNASAI@localhost exp13]$ sh8fiba.sh 4fibonacci seroes up to 4 numbers0112
awk 'BEGIN {a=0;b=1; while(++x<=10){print a; t=a;a=a+b;b=t}; exit}'
CSE ([email protected] II-Sem) EXP-13
Page 9 of 38bphanikrishna.wordpress.comFOSSLAB
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 EAvg<70&&Avg>=60 then grade C Else grade F
[KRISHNASAI@localhost exp13]$ cat 9stum.shecho "Enter Student name"read nameecho "Enter Student Registered Number"read regecho "Enter the marks of five subjects : "read m1 m2 m3 m4 m5let total=$m1+$m2+$m3+$m4+$m5let per=(total/5)echo Name :$nameecho Registered number :$regecho student total marks:$totalecho Student percentage :$perif [ $per -ge 80 ]thenecho gread :Aelif [ $per -ge 70 -a $per -lt 80 ]thenecho Gread :Belif [ $per -ge 60 -a $per -lt 70 ]thenecho Gread :Celif [ $per -ge 50 -a $per -lt 60 ]thenecho Gread :Delif [ $per -ge 40 ] && [ $per -lt 50 ]thenecho Gread :Eelseecho "Gread :F(fail) "fiOUTPUT:-[KRISHNASAI@ exp13]$ sh 9stum.shEnter Student namekrishnasaiEnter Student Registered Number11275715034Enter the marks of five subjects :90 85 90 95 80
Name :krishnasaiRegistered number :11275715034student total marks:440Student percentage :88gread :A
CSE ([email protected] II-Sem) EXP-13
Page 10 of 38bphanikrishna.wordpress.comFOSSLAB
10. Write a shell script to accept empno,empname,basic. Find DA,HRA,TA,PF usingfollowing rules. Display empno, empname, basic, DA,HRA,PF,TA,GROSS SAL andNETSAL. Also store all details in a file called emp.datRules:HRA is 18% of basic if basic > 5000 otherwise 550DA is 35% of basicPF is 13% of basicIT is 14% of basicTA is 10% of basic
Program:[KRISHNASAI@H exp13]$ vi 10salary.shecho "Enter the EmployeeID (empno)"read empnoecho "Enter the Name of Employee"read empnameecho "enter the basic salary:"read bsalbsalp=`expr $bsal / 100`if [ $bsal -gt 5000 ]thenhra=`expr $bsalp \* 18`elsehra=550fida=`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.datecho "Empname : $empname"|tee cat >> emp.datecho "Basic : $bsal"|tee cat >> emp.datecho "HRA(House Rent Allowance): $hra"|tee cat >> emp.datecho "PF (Provident fund) : $pf"|tee cat >> emp.datecho "TA (Travalling Allowance): $ta"|tee cat >> emp.datecho "IT (Income Tax) : $it"|tee cat >> emp.datecho "Gross salary : $gross"|tee cat >> emp.datecho "netsalary : $netsal"|tee cat >>emp.datOutput:[KRISHNASAI@H exp13]$ sh 10salary.shEnter the EmployeeID (empno)1234Enter the Name of Employeekrishnasaienter the basic salary:25000
CSE ([email protected] II-Sem) EXP-13
Page 11 of 38bphanikrishna.wordpress.comFOSSLAB
Empno : 1234[KRISHNASAI@H exp13]$ cat emp.datEmpno : 1234Empname : krishnasaiBasic : 25000HRA(House Rent Allowance): 4500PF (Provident fund) : 3250TA (Travalling Allowance): 2500IT (Income Tax) : 3500Gross salary : 40750netsalary : 34000TA = BASIC SAL*PERCENTAGE/100DA= BASIC SAL*PERCENTAGE/100HRA= BASIC SAL*PERCENTAGE/100GROSS SAL =BASIC SAL+ TA + DA + HRAPF= GROSS SAL*PERCENTAGE/100NET SAL = GROSS SAL -( PF + LIC+IT)
Gross Salary: is the amount of salary paid after adding all benefits and allowances andbefore 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 likeloan or bond re-payments.
Cost to Company: Companies use the term “Cost to Company” to calculate the total cost toemploy. I.e. all the costs associated with an employment contract. Major part of CTCcomprises of compulsory deductibles. These include deductions for provident fund, medicalinsurance etc. They form a part of your compensation structure but you not get them as a partof in-hand salary. As such, although it increases your CTC, it does not increment your netsalary.
CSE ([email protected] II-Sem) EXP-13
Page 12 of 38bphanikrishna.wordpress.comFOSSLAB
11. Write a shell script to demonstrate break and continue statements
Program: beak[KRISHNASAI@Hexp13]$vi11break.shval="1 2 3 4 5 6 7 8 9 10"for num in $valdo
e=`expr $num % 2`if [ $e -eq 0 ]then
echo "$num Number is an evennumber!!"
continuefiecho "$num is odd number"
if [ $num -eq 5 ]thenbreakfidone
Program: continue[KRISHNASAI@Hexp13]$ vi 11continu.shval="1 2 3 4 5 6 7 8 9 10"for num in $valdo
e=`expr $num % 2`if [ $e -eq 0 ]then
echo "$num Number is an evennumber!!"
continuefiecho "$num is odd number"
done
Output:[KRISHNASAI@H exp13]$ sh 11break.sh1 is odd number2 Number is an even number!!3 is odd number4 Number is an even number!!5 is odd number
Output:[KRISHNASAI@Hexp13]$ sh 11continu.sh1 is odd number2 Number is an even number!!3 is odd number4 Number is an even number!!5 is odd number6 Number is an even number!!7 is odd number8 Number is an even number!!9 is odd number10 Number is an even number!!
To stop a loop or skip iterations of the loop two statements used to control shellloops:
1. The break statement2. The continue statement
The infinite Loop:All the loops have a limited life and they come out once the condition is false or truedepending on the loop.A loop may continue forever due to required condition is not met. A loop thatexecutes forever without terminating executes an infinite number of times. For thisreason, such loops are called infinite loops.
Example:
CSE ([email protected] II-Sem) EXP-13
Page 13 of 38bphanikrishna.wordpress.comFOSSLAB
Here is a simple example that uses the while loop to display the numbers zero to nine:
#!/bin/sha=10while [ $a -ge 10 ]do
echo $aa=`expr $a + 1`
done
This loop would continue forever because a is alway greater than or equal to 10 and itwould 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, aftercompleting the execution of all of the lines of code up to the break statement. It thensteps 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 abecomes 5:
#!/bin/sha=0while [ $a -lt 10 ]do
echo $aif [ $a -eq 5 ]then
breakfia=`expr $a + 1`
done
This will produce following result:
012345
Here is a simple example of nested for loop. This script breaks out of both loops ifvar1 equals 2 and var2 equals 0:
#!/bin/sh
for var1 in 1 2 3do
for var2 in 0 5do
CSE ([email protected] II-Sem) EXP-13
Page 14 of 38bphanikrishna.wordpress.comFOSSLAB
if [ $var1 -eq 2 -a $var2 -eq 0 ]then
break 2else
echo "$var1 $var2"fi
donedone
This will produce following result. In the inner loop, you have a break command withthe argument 2. This indicates that if a condition is met you should break out of outerloop and ultimately from inner loop as well.
1 01 5
The continue statement:The continue statement is similar to the break command, except that it causes thecurrent 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 thenext iteration of the loop.
Syntax:
continue
Like with the break statement, an integer argument can be given to the continuecommand to skip commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.
CSE ([email protected] II-Sem) EXP-13
Page 15 of 38bphanikrishna.wordpress.comFOSSLAB
12. Write a shell script to satisfy the following menu optionsa) Display current directory pathb) Display todays datec) Display users who are connected to the unix systemd) Quit
[KrishnaSAI@H exp13]$ vi 12someactions.shch=0while [ $ch -ne 4 ]doclearecho "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 chcase $ch in1)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>userlisti=0for u in `who|cut -d" " -f1`doi=`expr $i + 1`doneecho "Total number of users are : $i "echo "login user details in `date +"%D %H-%M-%S "`"echo "---------------------------------"who|cut -d" " -f1echo "--------------------------------";;4)echo "Have a nice time"exit;;*)echo "Invalid choice entered";;esacecho "are you continue (1 for yes / 0 for No)"
CSE ([email protected] II-Sem) EXP-13
Page 16 of 38bphanikrishna.wordpress.comFOSSLAB
read tempif [ $temp -eq 0 ]thench=4fidone
Output:1.Display current dir2.Display Today date3.Display users who are connected to the unixsystem4.ExitEnter your choice1Current Dir is :/home/CSESTAFF/krishna/foss/exp13are you continue (1 for yes / 0 for No)
Enter your choice2Today date isToday is :ThursdayToday date is :12-March-2015Time :04:28:04 PM ||+0530are you continue (1 for yes / 0 for No)
Enter your choice3Users who are connected to shellTotal number of users are : 3login user details in 03/12/15 16-28-23---------------------------------CSESTAFFCSESTAFFCSESTAFF--------------------------------are you continue (1 for yes / 0 for No)
Enter your choice4Have a nice time
CSE ([email protected] II-Sem) EXP-13
Page 17 of 38bphanikrishna.wordpress.comFOSSLAB
13. Write a shell script to delete all files whose size is zero bytes from current directory
Program:[KRISHNASAI@localhost exp13]$ cat 13delempa.shecho "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`doecho "do you want to remove the {[ $i ]} file form this folder ( Press Y for yes, elseN) "read deif [ "$de" == "y" ]thenrm $iecho $i removedfidoneif [ "$i" == "" ]thenecho "In `pwd` there are no empty files"fiOutput:Your present working directory is/home/KRISHNASAI/krishna/foss/exp13FIles whose size is zero bytes are----------------------------------hhhhhhhhhh2hhhhh1hh----------------------------------do you want to remove the {[ hhhhh ]} file form this folder ( Press Y for yes, else N)yhhhhh removeddo you want to remove the {[ hhhhh2 ]} file form this folder ( Press Y for yes, else N)nfind -type f -size 0 -ls
CSE ([email protected] II-Sem) EXP-13
Page 18 of 38bphanikrishna.wordpress.comFOSSLAB
14. Write a shell script to display string palindrome from given arguments
for n in $*dos=`echo $n | wc -c`while [ $s -gt 0 ]dotemp=`echo $n | cut -c $s`s=`expr $s - 1`temp1="$temp1$temp"doneecho "Reverse string of # $n # is $temp1"if [ $n != $temp1 ]thenecho "$n is not palandrome"elseecho "$n is palandrome"
fitemp1=""doneOutput:[KRISHNASAI@localhost exp13]$ sh 14palindrome.sh malayalam 451Reverse string of # malayalam # is malayalammalayalam is palandromeReverse string of # 451 # is 154451 is not palandrome
CSE ([email protected] II-Sem) EXP-13
Page 19 of 38bphanikrishna.wordpress.comFOSSLAB
15. Write a shell script which will display Armstrong numbers from given givenarguments.
[KRISHNASAI@localhost exp13]$ vi15amg.shecho "Enter a number: "read cx=$csum=0r=0n=0while [ $x -gt 0 ]dor=`expr $x % 10`n=`expr $r \* $r \* $r`sum=`expr $sum + $n`x=`expr $x / 10`doneif [ $sum -eq $c ]thenecho "It is an Armstrong Number."elseecho "It is not an Armstrong Number."fi
[KRISHNASAI@localhost exp13]$ vi15amga.shfor c in $*dox=$csum=0r=0n=0while [ $x -gt 0 ]dor=`expr $x % 10`n=`expr $r \* $r \* $r`sum=`expr $sum + $n`x=`expr $x / 10`done
if [ $sum -eq $c ]thenecho " $c is an Armstrong Number."elseecho " $c is not an Armstrong Number."fidone
[KRISHNASAI@localhost exp13]$ sh15amg.shEnter a number:143It is not an Armstrong Number.[KRISHNASAIS@localhost exp13]$ sh15amg.shEnter a number:153It is an Armstrong Number.
[KRISHNASAI@localhost exp13]$ sh15amga.sh 143 153 125143 is not an Armstrong Number.153 is an Armstrong Number.125 is not an Armstrong Number.
CSE ([email protected] II-Sem) EXP-13
Page 20 of 38bphanikrishna.wordpress.comFOSSLAB
16. Write a shell script to display reverse numbers from given argument list
[KRISHNASAI@ exp13]$ vi 16res.shfor n in $*dos=`echo $n | wc -c`while [ $s -gt 0 ]dotemp=`echo $n | cut -c $s`s=`expr $s - 1`temp1="$temp1$temp"doneecho "Reverse string of # $n # is $temp1"temp1=""done
[KRISHNASAIS@exp13]$ cat16resaa.shfor n in $*dos=0m=$nwhile [ $n -gt 0 ]dor=`expr $n % 10`s=`expr $s \* 10 + $r`n=`expr $n / 10`doneecho "Reverse of $m is" $sdone
Output:[KRISHNASAI@ exp13]$ sh 16res.shkrishnasai 143Reverse string of # krishnasai # isiasanhsirkReverse string of # 143 # is 341
[KRISHNASAI@exp13]$sh 16resaa.sh987 890 121Reverse of 987 is 789Reverse of 890 is 98Reverse of 121 is 121
17. Write a shell script to display factorial value from given argument list
Program:[KRISHNASAI@localhost exp13]$ vi 17fact.shi=1f=1echo " Enter the number"read nwhile [ $i -le $n ]dof=`expr $f \* $i`i=`expr $i + 1`doneecho FACTORIAL of a given number $n is: $f[KRISHNASAI@localhost exp13]$Output:[KRISHNASAI@localhost exp13]$ sh 17fact.shEnter the number5FACTORIAL of a given number 5 is: 120[KRISHNASAI@localhost exp13]$ sh 17fact.shEnter the number3FACTORIAL of a given number 3 is: 6
CSE ([email protected] II-Sem) EXP-13
Page 21 of 38bphanikrishna.wordpress.comFOSSLAB
18. Write a shell script which will find maximum file size in the given argument list
Program:[KRISHNASAI@H exp13]$ cat maxsize.shmax=0for k in $*dofor i in `ls -l $k|tr -s " "|cut -f 5 -d " "`doif [ $max -le $i ]thenmax=$if=$kfidonedoneecho maximum size file name is : $fecho $f size is :$max
Output:[KRISHNASAI@H exp13]$ sh maxsize.sh kkw lik sssmaximum size file name is : ssssss size is :59
Verification:[KRISHNASAI@H exp13]$ wc kkw4 9 47 kkw[KRISHNASAI@H exp13]$ wc lik0 0 0 lik[KRISHNASAI@H exp13]$ wc sss1 5 59 sss[KRISHNASAI@H exp13]$
CSE ([email protected] II-Sem) EXP-13
Page 22 of 38bphanikrishna.wordpress.comFOSSLAB
19. Write a shell script which will greet you “Good Morning”, ”Good Afternoon”, “GoodEvening’ and “Good Night” according to current time.
[KRISHNASAI@localhost exp13]$ cat 19time.shhournow=`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.;;EsacOutput:[KRISHNASAI@localhost exp13]$ sh 19time.sh.Good Evening Mr/Ms :KRISHNASAI.
CSE ([email protected] II-Sem) EXP-13
Page 23 of 38bphanikrishna.wordpress.comFOSSLAB
20. Write a shell script to sort the elements in a array using bubble sort technique
Program:
[KRISHNASAI@localhost exp13]$ cat 20bubblea.shecho "enter maximum number"read n# taking input from userecho "enter Numbers in array:"for (( i = 0; i < $n; i++ ))doread nos[$i]done#printing the number before sortingecho "Numbers in an array are:"for (( i = 0; i < $n; i++ ))doecho ${nos[$i]}done# Now do the Sorting of numbersfor (( i = 0; i < ( $n - 1 ) ; i++ ))dofor (( j = 0; j < ( $n - $i - 1); j++ ))doh=`expr $j + 1`if [ ${nos[$j]} -gt ${nos[ $h]} ]; thent=${nos[$j]}nos[$j]=${nos[$h]}nos[$h]=$tfidonedone# Printing the sorted numberecho -e "\n Sorted Numbers "for (( i=0; i < $n; i++ ))doecho ${nos[$i]}doneOutput:[KRISHNASAI@localhost exp13]$ sh 20bubblea.shenter maximum number5enter Numbers in array:8-1-086Numbers in an array are:8-1-08
CSE ([email protected] II-Sem) EXP-13
Page 24 of 38bphanikrishna.wordpress.comFOSSLAB
6
Sorted Numbers-1-0688Description:
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm thatrepeatedly steps through the list to be sorted, compares each pair of adjacent itemsand swaps them if they are in the wrong order. The pass through the list is repeateduntil 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 togreatest number using bubble sort. In each step, elements written in bold are beingcompared. Three passes will be required.
First Pass:( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, andswaps 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 )
CSE ([email protected] II-Sem) EXP-13
Page 25 of 38bphanikrishna.wordpress.comFOSSLAB
21. Write a shell script to find largest element in a array
Program:[krishnasai@dnrcet ~]$ vi 21bignum.shecho "enter maximum number"read n# taking input from userecho "enter Numbers in array:"for (( i = 0; i < $n; i++ ))doread nos[$i]done#Finding largest number in given arrayecho "Numbers in an array are:"for (( i = 0; i < $n; i++ ))doecho ${nos[$i]}doneres=${nos[1]}for (( i=1; i < $n; i++))doif [ $res -le ${nos[$i]} ]thenres=${nos[$i]}fidoneecho "Maximum element among the given $n elements is"echo "$res"Output:[krishnasai@dnrcet ~]$ sh 21bignum.shenter maximum number5enter Numbers in array:6915619Numbers in an array are:6915619Maximum element among the given 5 elements is19[krishnasai@dnrcet ~]$
CSE ([email protected] II-Sem) EXP-13
Page 26 of 38bphanikrishna.wordpress.comFOSSLAB
22. Write an awk program to print sum, avg of students marks list
[KrishnaSAI@H exp13]$ cat avg1.awk# BeginBEGIN {
tot=0;}# Dev{
name[NR]=$1;total[NR]=($2 + $3 + $4)average[NR]=total[NR]/ 3;
tot=tot + 1;}
# EndEND {print "there are "tot" students, their averageis:\n";
i = 1;while (i <= tot){
printf("Name :%-10s \n Total:%d \n Average:%.2f \n", name[i] ,total[i], average[i++]);}
}[KrishnaSAI@H exp13]$ cat studentskrishna 75 75 80ravi 70 80 90pushpa 80 90 55lakshmi 60 78 67[KrishnaSAI@H exp13]$
Output:[KrishnaSAI@H exp13]$ awk -favg1.awk students
there are 4 students, their average is:
Name :krishnaTotal:230Average: 76.67Name :raviTotal:240Average: 80.00Name :pushpaTotal:225Average: 75.00Name :lakshmiTotal:205Average: 68.33[KrishnaSAI@H exp13]$
CSE ([email protected] II-Sem) EXP-13
Page 27 of 38bphanikrishna.wordpress.comFOSSLAB
23. Write an awk program to display students pass/fail report
[KrishnaSAI@H exp13]$ cat pf.awk# BeginBEGIN {
tot=0;}
# Dev{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;}
# EndEND {
print "there are "tot" students, their averageis:\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]$ catstuddataKrishna 75 80 95Ravi 85 94 79Pushpa 90 90 90Lakshmi 80 80 80rama 30 35 35
[KrishnaSAI@H exp13]$ awk -f pf.awk studdatathere are 5 students, their average is:
Name TotalMarks Average StatusKrishna 250 83.33 PassRavi 258 86.00 PassPushpa 270 90.00 PassLakshmi 240 80.00 Passrama 100 33.33 fail[KrishnaSAI@H exp13]$
CSE ([email protected] II-Sem) EXP-13
Page 28 of 38bphanikrishna.wordpress.comFOSSLAB
24. Write an awk program to count the no. of vowels in a given file
Program:[KRISHNASAI@H exp13]$ cat ffawk.awkBEGIN {
FS = " "; # Space separates wordsline_count = 0; # Number of linesword_count = 0; # Number of wordschar_count = 0 # Number of charactersvowel=0;cons=0;spe=0;num=0;
}{
line_count++; # Count the next lineword_count += NF; # Word count in line = NFchar_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++}
CSE ([email protected] II-Sem) EXP-13
Page 29 of 38bphanikrishna.wordpress.comFOSSLAB
END {printf "Number of lines = %d\n", line_countprintf "Number of words = %d\n", word_countprintf "Number of characters = %d\n", char_countprintf "No of lines not contain vowel = %d \n",kprintf "No of lines contain vowel = %d \n",vprintf "Number of vowels in a given file = %d \n",vowelprintf "Number of consonents in a given file= %d \n", consprintf "Number of Numerical data [0-9] in a given file = %d \n",numprintf "Number of specail characters = %d \n",spe
}
[KRISHNASAI@H exp13]$ cat kkwhi how are youtell memy dry345%$9
Output:
[KRISHNASAI@H exp13]$ awk -f ffawk.awk kkwNumber of lines = 6Number of words = 10Number of characters = 39No of lines not contain vowel = 4No of lines contain vowel = 2Number of vowels in a given file = 8Number of consonents in a given file= 14Number of Numerical data [0-9] in a given file = 4Number of specail characters = 7[KRISHNASAI@H exp13]$
CSE ([email protected] II-Sem) EXP-13
Page 30 of 38bphanikrishna.wordpress.comFOSSLAB
25. Write an awk program which will find maximum word and its length in the giveninput File
[KrishnaSAI@H awk]$ cat wcs.awkBegin {lineCount=1maxi=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=lenw=wor}print(wor,len) }} $1printf("maximum size of the word in the abouve line is :");print(w,maxi)}Output:[KrishnaSAI@H awk]$ cat fWithout doing work nothing is yoursit better to die with memories then to live only in dreamok[KrishnaSAI@H awk]$ awk -f wcs.awk fWithout 7doing 5work 4nothing 7is 2yours 5maximum size of the word in the abouve line is :nothing 7it 2better 6to 2die 3with 4memories 8then 4to 2live 4only 4in 2dream 5maximum size of the word in the abouve line is :memories 8ok 2maximum size of the word in the abouve line is :memories 8[KrishnaSAI@H awk]$
CSE ([email protected] II-Sem) EXP-13
Page 31 of 38bphanikrishna.wordpress.comFOSSLAB
26. Write a shell script to generate the mathematical tables.
[KRISHNASAI@localhost exp13]$ cat 26mt.shecho "Enter a number:"read necho "enter a table range"read recho "Multiplication table of $n is:"for (( i=1; i<=$r; i++ ))doresult=$[ $n * $i ]echo $n "*" $i = $resultdoneOutput:[KRISHNASAI@localhost exp13]$ sh 26mt.shEnter a number:3enter a table range3Multiplication table of 3 is:3 * 1 = 33 * 2 = 63 * 3 = 9
CSE ([email protected] II-Sem) EXP-13
Page 32 of 38bphanikrishna.wordpress.comFOSSLAB
27. Write a shell script to sort elements of given array by using selection sort.
Program:[KSAI@Hexp13]$ vi 27selectionsort.shecho "Enter size of an aray"read n# taking input from userecho "enter elements in array:"for (( i = 0; i < $n; i++ ))doread arr[$i]done#printing the number before sortingecho "Numbers in an array are:"for (( i = 0; i < $n; i++ ))doecho ${arr[$i]}done# selection sorting operationsfor (( i = 0; i < ( $n - 1 ) ; i++ ))domin=${arr[$i]}index=$ifor (( j = i+1; j < $n; j++ ))doif [ ${arr[$j]} -lt $min ]thenmin=${arr[$j]}index=$jfidonet=${arr[$i]}arr[$i]=${arr[$index]}arr[$index]=$tdone# Printing the sorted numberecho "\n after SELECTION SORT "for (( i=0; i < $n; i++ ))doecho ${arr[$i]}done
Output:[KSAI@Hexp13]$ sh 27selectionsort.shEnter size of an aray5enter elements in array:91516Numbers in an array are:91516after SELECTION SORT11569[KSAI@Hexp13]$
CSE ([email protected] II-Sem) EXP-13
Page 33 of 38bphanikrishna.wordpress.comFOSSLAB
28. Write a shell script to search given number using binary search.
Program:[krishnasai@localhost ~]$ vi 28binarysearch.shecho "enter maximum number"read n# taking input from userecho "enter Numbers in array:"for (( i = 0; i < $n; i++ ))doread nos[$i]done#printing the number before sortingecho "Numbers in an array are:"for (( i = 0; i < $n; i++ ))doecho ${nos[$i]}done#find elementecho "Enter the key element whom you want to search in given $n elements"read keylow=0high=`expr $n - 1`count=0while [ $count -eq 0 -a $high -ge $low ]dom=`expr $low + $high`mid=`expr $m / 2`if [ $key -eq ${nos[$mid]} ]thencount=1elif [ $key -gt ${nos[$mid]} ]thenlow=`expr $mid + 1`elsehigh=`expr $mid - 1`fidoneif [ $count -eq 1 ]thenecho "the given key { $key }is found at { $mid } position"elseecho "given key $key is not found"fi
CSE ([email protected] II-Sem) EXP-13
Page 34 of 38bphanikrishna.wordpress.comFOSSLAB
Output:[krishnasai@localhost ~]$ sh 28buublesort.shenter maximum number5enter Numbers in array:7891419Numbers in an array are:7891419Enter the key element whom you want to search in given 5 elements9the given key { 9 }is found at { 2 } position
CSE ([email protected] II-Sem) EXP-13
Page 35 of 38bphanikrishna.wordpress.comFOSSLAB
29. Write a shell script to find number of vowels, consonants, numbers, white spaces andspecial characters in a given string.
[KRISHNASAI@localhost exp13]$ cat 29countvcs.shclearecho "Type any String"read stringlength=`echo $string|wc -c`nvowels=0nconsonants=0ndigits=0nsymbols=0leng=`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`
esacdoneecho "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.shType any StringKrishnasai4all $KRISHNASAI$String is : Krishnasai4all $KRISHNASAI$Length of given string: 20Number of Vowels : 6Number of Consonants : 10Number of Digits : 1Number of special char: 3
CSE ([email protected] II-Sem) EXP-13
Page 36 of 38bphanikrishna.wordpress.comFOSSLAB
30. Write a shell script to lock the terminal.
Program:[KRISHNASAI@localhost exp13]$ vi 30terminal.shclearstty -echoecho "enter password to lock the terminal"read pass1echo " Re-enter password"read pass2if [ "$pass1" = "$pass2" ]thenecho "system is locked"echo "enter password to unlock"trap ``/1 2 3 9 15 18while truedoread pass3if [ $pass1 = $pass3 ]then echo "system unlocked"stty echoexitelseecho "password mismatch"fidoneelseecho "password mismatch"stty echofi[KRISHNASAI@localhost exp13]$Output:[KRISHNASAI@localhost exp13]$ sh 30terminal.shenter password to lock the terminalRe-enter passwordsystem is lockedenter password to unlockpassword mismatchsystem unlockedDescription:
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.
CSE ([email protected] II-Sem) EXP-13
Page 37 of 38bphanikrishna.wordpress.comFOSSLAB
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 serial port, 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 (xterm, rxvt, or zterm). All these use software to emulate a real terminal.
Setty:stty changes and prints terminal line settingsSyntaxstty [-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.
Examplesstty 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 shellprogram, normally that program is immediately terminated, and your command promptreturned. This may not always be desirable. For instance, you may end up leaving a bunch oftemporary files that won't get cleaned up.Trapping these signals is quite easy, and the trap command has the following syntax:
$ trap commands signals
CSE ([email protected] II-Sem) EXP-13
Page 38 of 38bphanikrishna.wordpress.comFOSSLAB
Here command can be any valid Unix command, or even a user-defined function, and signalcan 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 files2. Ignore signals
Cleaning Up Temporary Files:As an example of the trap command, the following shows how you can remove some filesand 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 twofiles work1$$ and dataout$$ will be automatically removed if signal number 2 is received bythe program.So if the user interrupts execution of the program after this trap is executed, you can beassured that these two files will be cleaned up. The exit command that follows the rm isnecessary because without it execution would continue in the program at the point that it leftoff when the signal was received.Signal number 1 is generated for hangup: Either someone intentionally hangs up the line orthe line gets accidentally disconnected.You can modify the preceding trap to also remove the two specified files in this case byadding 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 onecommand. Also note that the shell scans the command line at the time that the trap commandgets 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 timethat the trap command is executed. If you wanted this substitution to occur at the time thateither signal 1 or 2 was received you can put the commands inside single quotes:
$ trap 'rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit' 1 2