Shell Programming 185253

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

Shell Programming 185253Computer Practice II cseannauniv.blogspot.

com Vijai Anand

Ex. No: 2.1 SIMPLE SHELL PROGRAMS Aim To write simple shell scripts using shell programming fundamentals. The activities of a shell are not restricted to command interpretation alone. The shell also has rudimentary programming features. When a group of commands has to be executed regularly, they are stored in a file (with extension . sh). All such files are called shell scripts or shell programs. Shell programs run in interpretive mode. The original UNIX came with the Bourne shell (sh) and it is universal even today. Then came a plethora of shells offering new features. Two of them, C shell ( csh) and Korn shell (ksh) has been well accepted by the UNIX fraternity. Linux offers Bash shell ( bash) as a superior alternative to Bourne shell.

Preliminaries

1. Comments in shell script start with #. It can be placed anywhere in a line; the shell

ignores contents to its right. Comments are recommended but not mandatory 2. Shell variables are loosely typed i.e. not declared. Their type depends on the value assigned. Variables when used in an expression or output must be prefixed by $. 3. The read statement is shell's internal tool for making scripts interactive. 4. Output is displayed using echo statement. Any text should be within quotes. Escape sequence should be used with e option. 5. Commands are always enclosed with ` ` (back quotes). 6. Expressions are computed using the expr command. Arithmetic operators are + * / %. Meta characters * ( ) should be escaped with a \. 7. Multiple statements can be written in a single line separated by ; 8. The shell scripts are executed using the sh command (sh filename). Result Thus using programming basics, simple shell scripts were executed
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.1.ASwapping values of two variables Algorithm Step 1 : Start Step 2 : Read the values of a and b Step 3 : Interchange the values of a and b using another variable t as follows: t=a a=b b=t Step 4 : Print a and b Step 5 : Stop Program (swap.sh) # Swapping values echo -n "Enter value for A : " read a echo -n "Enter value for B : " read b t=$a a=$b

b=$t echo "Values after Swapping" echo "A Value is $a" echo "B Value is $b" Output [vijai@localhost simple]$ sh swap.sh Enter value for A : 12 Enter value for B : 23 Values after Swapping A Value is 23 B Value is 12 2.1.BFarenheit to Centigrade Conversion Algorithm Step 1 : Start Step 2 : Read fahrenheit value Step 3 : Convert fahrenheit to centigrade using the formulae: (fahrenheit 32) 5/9 Step 4 : Print centigrade Step 5 : Stop
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Program (degconv.sh) # Degree conversion echo -n "Enter Fahrenheit : " read f c=`expr \( $f - 32 \) \* 5 / 9` echo "Centigrade is : $c" Output [vijai@localhost simple]$ sh degconv.sh Enter Fahrenheit : 213 Centigrade is : 100 2.1.C Area & Circumference of Circle Algorithm Step 1 : Start Step 2 : Define constant pi = 3.14 Step 3 : Read the value of radius Step 4 : Calculate area using formulae: pi radius2 Step 5 : Calculate circumference using formulae: 2 pi radius Step 6 : Print area and circumference Step 7 : Stop Program (circle.sh) # Circle metrics using readonly variable pi=`expr "scale=2; 22 / 7" | bc` readonly pi # pi value cannot be altered echo -n "Enter value for radius : " read radius area=`expr "scale=2; $pi * $radius * $radius" | bc` circum=`expr "scale=2; 2 * $pi * $radius" | bc` echo "Area : $area" echo "Circumference : $circum"

Output [vijai@localhost simple]$ sh circle.sh Enter value for radius : 12 Area : 452.16 Circumference : 75.36
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.1.D Simple Interest Calculation Algorithm Step 1 : Start Step 2 : Read the values principal, rate and years Step 3 : Compute simpleinterest using the formulae: (principal rate years) / 100 Step 4 : Print simpleinterest Step 5 : Stop Program (simpint.sh) # Interest computation using bc echo -n "Enter Principal amount : " read p echo -n "Enter number of years : " read n echo -n "Enter rate of interest : " read r si=`expr "scale=2; $p * $n *$r / 100" | bc` echo "Simple Interest : $si" Output [vijai@localhost simple]$ sh simpint.sh Enter Principal amount : 1285 Enter number of years : 3 Enter rate of interest : 5 Simple Interest : 192.75
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Ex. No: 2.2 CONDITIONAL CONSTRUCTS Aim To write shell scripts using decision-making constructs. Shell supports decision-making using if statement. The if statement like its counterpart in programming languages has the following formats. The first construct executes the statements when the condition is true. The second construct adds an optional else to the first one that has different set of statements to be executed depending on whether the condition is true or false. The last one is an elif ladder, in which conditions are tested in sequence, but only one set of statements is executed.
if [ condition ] then statements fi if [ condition ] then statements else statements

fi if [condition ] then statements elif [ condition ] then statements .. . else statements fi

The set of relational and logical operators used in conditional expression is given below. The numeric comparison in the shell is confined to integer values only. Operator Description -eq Equal to -ne Not equal to -gt Greater than -ge Greater than or equal to -lt Less than -le Less than or equal to -a Logical AND -o Logical OR ! Logical NOT Result Thus using if statement scripts with conditional expressions were executed
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.2.A Odd or even Algorithm Step 1 : Start Step 2 : Read number Step 3 : If number divisible by 2 then Print "Number is Even" Step 3.1 : else Print "Number is Odd" Step 4 : Stop Program (oddeven.sh) # Odd or even using if-else echo -n "Enter a non-zero number : " read num rem=`expr $num % 2` if [ $rem -eq 0 ] then echo "$num is Even" else echo "$num is Odd" fi Output [vijai@localhost decision]$ sh oddeven.sh

Enter a non-zero number : 12 12 is Even 2.2.BBiggest of 3 numbers Algorithm Step 1 : Start Step 2 : Read values of a, b and c Step 3 : If a > b and a > c then Print "A is the biggest" Step 3.1 : else if b > c then Print "B is the biggest " Step 3.2 : else Print "C is the biggest" Step 4 : Stop
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Program (big3.sh) # Biggest using logical expression echo -n "Give value for A B and C: " read a b c if [ $a -gt $b -a $a -gt $c ] then echo "A is the Biggest number" elif [ $b -gt $c ] then echo "B is the Biggest number" else echo "C is the Biggest number" fi Output [vijai@localhost decision]$ sh big3.sh Give value for A B and C: 4 3 4 C is the Biggest number 2.2.CLeap year Algorithm Step 1 : Start Step 2 : Read the value of year Step 3 : If year divisible by 400 then Print "Leap year" Step 3.1 : else if year divisible by 4 and not divisible by 100 then Print "Leap year" Step 3.2 : else Print "Not a leap year" Step 4 : Stop Program (leap.sh) # Leap year echo -n "Enter a year : " read year rem1=`expr $year % 4` rem2=`expr $year % 100`

rem3=`expr $year % 400` if [ $rem3 -eq 0 ] then echo "$year is a Leap Year" elif [ $rem2 -ne 0 -a $rem1 -eq 0 ] then echo "$year is a Leap Year" else echo "$year is Not a leap year" fi
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Output [vijai@localhost decision]$ sh leap.sh Enter a year : 1900 1900 is Not a leap year 2.2.DGrade Determination Algorithm Step 1 : Start Step 2 : Read mark Step 3 : If mark > 90 then Print "S grade" Step 3.1 : else if mark > 80 then Print "A grade" Step 3.2 : else if mark > 70 then Print "B grade" Step 3.3 : else if mark > 60 then Print "C grade" Step 3.4 : else if mark > 55 then Print "D grade" Step 3.5 : else if mark 50 then Print "E grade" Step 3.6 : else Print "U grade" Step 4 : Stop Program (grade.sh) echo -n "Enter the mark : " read mark if [ $mark -gt 90 ] then echo "S Grade" elif [ $mark -gt 80 ] then echo "A Grade" elif [ $mark -gt 70 ] then echo "B Grade" elif [ $mark -gt 60 ] then

echo "C Grade" elif [ $mark -gt 55 ] then echo "D Grade"
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

elif [ $mark -ge 50 ] then echo "E Grade" else echo "U Grade" fi Output [vijai@localhost decision]$ sh grade.sh Enter the mark : 65 C Grade 2.2.EString comparison Algorithm Step 1 : Start Step 2 : Read strings str1 and str2 Step 3 : If str1 = str2 then Print "Strings are the same" Step 3.1 : else Print "Strings are distinct" Step 4 : Stop Program (strcomp.sh) echo -n "Enter the first string : " read s1 echo -n "Enter the second string : " read s2 if [ $s1 == $s2 ] then echo "Strings are the same" else echo "Strings are distinct" fi Output [vijai@localhost decision]$ sh strcomp.sh Enter the first string : ece-a Enter the second string : ECE-A Strings are distinct
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.2.FEmployee Pay Calculation Algorithm Step 1 : Start Step 2 : Read basic Step 3 : If basic > 30000 then hra is 5% of basic

da is 5% of basic tax is 10% of basic Step 3.1 : else if basic > 20000 then hra is 4% of basic da is 3% of basic tax is 8% of basic Step 3.2 : else hra is 3% of basic da is 2% of basic tax is 5% of basic Step 4 : Stop Program (emppay.sh) echo -n "Enter employee basic pay : " read basic if [ $basic -gt 30000 ] then hra=`expr 5 \* $basic / 100` da=`expr 5 \* $basic / 100` tax=`expr 10 \* $basic / 100` elif [ $basic -gt 20000 ] then hra=`expr 4 \* $basic / 100` da=`expr 3 \* $basic / 100` tax=`expr 8 \* $basic / 100` else hra=`expr 3 \* $basic / 100` da=`expr 2 \* $basic / 100` tax=`expr 5 \* $basic / 100` fi gross=`expr $basic + $da + $hra` netpay=`expr $gross - $tax` echo "Gross Pay : $gross" echo "Net Pay : $netpay" Output [vijai@localhost decision]$ sh emppay.sh Enter employee basic pay : 12000 Gross Pay : 12600 Net Pay : 12000
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Ex. No: 2.3 MULTI-WAY BRANCHING Aim To write shell scripts using case construct to match patterns. The case statement is used to compare a variables value against a set of constants (integer, character, string, range). If it matches a constant, then the set of statements followed after ) is executed till a ;; is encountered. The optional default block is indicated by *. Multiple constants can be specified in a single pattern separated by |.
case variable in constant1)

statements ;; constant2) statements ;; ... constantN) statements ;; *) statements esac

Result Thus using case statement, shell scripts were executed


Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.3.AVowel or Consonant Algorithm Step 1 : Start Step 2 : Read char Step 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then Print "It's a vowel" Step 3.1 : else Print "It's a consonant" Step 4 : Stop Program (vowel.sh) # Vowel with multiple values in a pattern echo -n "Key in a lower case character : " read choice case $choice in a|e|i|o|u) echo "It's a Vowel";; *) echo "It's a Consonant" esac Output [vijai@localhost multway]$ sh vowel.c Key in a lower case character : e It's a Vowel 2.3.BSimple Calculator Algorithm Step 1 : Start Step 2 : Read operands a and b Step 3 : Display operation menu Step 4 : Read option Step 5 : If option = 1 then Calculate c = a + b Step 5.1 : else if option = 2 then Calculate c = a b Step 5.2 : else if option = 3 then Calculate c = a * b Step 5.3 : else if option = 4 then Calculate c = a / b Step 5.4 : else if option = 5 then

Calculate c = a % b Step 5.5 : else Print "Invalid option" Step 6 : Print c Step 7 : Stop
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Program (calc.sh) # Arithmetic operations--multiple statements in a block echo -n "Enter the two numbers : " read a b echo " 1. Addition" echo " 2. Subtraction" echo " 3. Multiplication" echo " 4. Division" echo " 5. Modulo Division" echo -n "Enter the option : " read option case $option in 1) c=`expr $a + $b` echo "$a + $b = $c";; 2) c=`expr $a - $b` echo "$a - $b = $c";; 3) c=`expr $a \* $b` echo "$a * $b = $c";; 4) c=`expr $a / $b` echo "$a / $b = $c";; 5) c=`expr $a % $b` echo "$a % $b = $c";; *) echo "Invalid Option" esac Output [vijai@localhost multway]$ sh calc.sh Enter the two numbers : 2 4 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Modulo Division Enter the option : 1 2 + 4 = 6 2.3.CRental Options Algorithm Step 1 : Start Step 2 : Read vehicle Step 3 : If vehicle = "car" then Print "Rental is Rs. 20/km" Step 3.1 : else if vehicle = "van" then Print "Rental is Rs. 10/km"

Step 3.2 : else if vehicle = "jeep" then Print "Rental is Rs. 5/km" Step 3.3 : else if vehicle = "bicycle" then Print "Rental is Rs. 0.2/km"
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Step 3.4 : else Print "Vehicle not available" Step 4 : Stop Program (rental.sh) # String matching echo "Two/Four wheeler rental" echo -n "Enter the required vehicle : " read vehicle case $vehicle in "car") echo "For $vehicle Rs.20 per km";; "van") echo "For $vehicle Rs.10 per km";; "jeep") echo "For $vehicle Rs.5 per km";; "bicycle") echo "For $vehicle 20 paisa per km";; *) echo "Sorry, I cannot get a $vehicle for you";; esac Output [vijai@localhost multway]$ sh rental.sh Two/Four wheeler rental Enter the required vehicle : bicycle For bicycle 20 paisa per km 2.3.DVote Eligibility (vote.sh) Algorithm Step 1 : Start Step 2 : Read age Step 3 : If age 17 Print "Not eligible to vote" Step 3.1 : else Print "Eligible to vote" Step 4 : Stop Program # Vote--range matching echo -n "Enter your age : " read age case $age in [0-9]|1[0-7])echo "You are not eligible to vote";; *)echo "Eligible to vote" esac Output [vijai@localhost multway]$ sh vote.sh Enter your age : 12 You are not eligible to vote
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Ex. No: 2.4 LOOPING Aim To write shell scripts using looping statements. Shell supports a set of loops such as for, while and until to execute a set of statements repeatedly. The body of the loop is contained between do and done statement. The for loop doesn't test a condition, but uses a list instead.
for variable in list do statements done

The while loop executes the statements as long as the condition remains true. while [ condition ]
do

statements
done

The until loop complements the while construct in the sense that the statements are executed as long as the condition remains false. until [ condition ]
do

statements
done

Result Thus using loops, iterative scripts were executed


Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.4.AMultiplication Table Algorithm Step 1 : Start Step 2 : Read the value of n Step 3 : Initialize 1 to i Step 4 : Print n, i, ni Step 5 : Increment i by 1 Step 6 : Repeat steps 4 and 5 until i 10 Step 7 : Stop Program (multable.sh) # Multiplication table using for loop clear echo -n "Which multiplication table? : " read n for x in 1 2 3 4 5 6 7 8 9 10 do p=`expr $x \* $n` echo -n "$n X $x = $p" sleep 1 done Output [vijai@localhost loops]$ sh multable.sh Which multiplication table? : 6 6 X 1 = 6

6 X 2 = 12 6 X 3 = 18 6 X 4 = 24 6 X 5 = 30 6 X 6 = 36 6 X 7 = 42 6 X 8 = 48 6 X 9 = 54 6 X 10= 60 2.4.BArmstrong Number Algorithm Step 1 : Start Step 2 : Read number Step 3 : Initialize 0 to sum and number to num Step 4 : Extract lastdigit by computing number modulo 10 Step 5 : Cube the lastdigit and add it to sum Step 6 : Divide number by 10 Step 7: Repeat steps 46 until number > 0
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Step 8 : If sum = number then Print Armstrong number Step 8.1 : else Print Not an Armstrong number Step 9 : Stop Program (armstrong.sh) # Armstrong number using while loop echo -n "Enter a number : " read n a=$n s=0 while [ $n -gt 0 ] do r=`expr $n % 10` s=`expr $s + \( $r \* $r \* $r \)` n=`expr $n / 10` done if [ $a -eq $s ] then echo "Armstrong Number" else echo -n "Not an Armstrong number" fi Output [vijai@localhost loops]$ sh armstrong.sh Enter a number : 370 Armstrong Number 2.4.CNumber Reverse Algorithm

Step 1 : Start Step 2 : Read number Step 3 : Initialize 0 to reverse Step 4 : Extract lastdigit by computing number modulo 10 Step 5 : Compute reverse = reverse10 + lastdigit Step 6 : Divide number by 10 Step 7: Repeat steps 46 until number > 0 Step 8 : Print reverse Step 9 : Stop
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Program (reverse.sh) # To reverse a number using while loop echo -n "Enter a number : " read n rd=0 while [ $n -gt 0 ] do rem=`expr $n % 10` rd=`expr $rd \* 10 + $rem` n=`expr $n / 10` done echo "Reversed number is $rd" Output [vijai@localhost loops]$ sh reverse.sh Enter a number : 234 Reversed number is 432 2.4.DFibonacci Series Algorithm Step 1 : Start Step 2 : Read number of terms as n Step 3 : Initialize 0 to f1, 1 to f2 and 2 to i Step 4 : Print initial fibonacci terms f1, f2 Step 5 : Generate next term using the formula f3 = f1 + f2 Step 6 : Print f3 Step 7 : Increment i by 1 Step 8 : Assign f2 to f1 Step 9 : Assign f3 to f2 Step 10 : Repeat steps 59 until i n Step 11 : Stop Program (fibo.sh) # Fibonacci series using while loop echo -n "Enter number of terms : " read n echo "Fibonacci Series" f1=0 f2=1 echo -n "$f1 " echo -n " $f2 "

i=2
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

while [ $i -lt $n ] do f3=`expr $f1 + $f2` echo -n " $f3 " f1=$f2 f2=$f3 i=`expr $i + 1` done echo Output [vijai@localhost loops]$ sh fibo.sh Enter number of terms : 8 Fibonacci Series 0 1 1 2 3 5 8 13 2.4.EPrime Number Algorithm Step 1 : Start Step 2 : Read the value of n Step 3 : Initialize i to 2 Step 4 : If n is divisible by i then Print Not Prime and Stop Step 5 : Increment i by 1 Step 6 : Repeat steps 4 and 5 until i n/2 Step 7 : Print "Prime" Step 8 : Stop Program (prime.sh) # Prime number using exit echo -n "Enter the number : " read n i=2 m=`expr $n / 2` until [ $i -gt $m ] do q=`expr $n % $i` if [ $q -eq 0 ] then echo "Not a Prime number" exit fi i=`expr $i + 1` done echo "Prime number"
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Output [vijai@localhost loops]$ sh prime.sh

Enter the number : 17 Prime number 2.4.FFactorial Value Algorithm Step 1 : Start Step 2 : Read number Step 3 : Initialize 1 to fact and number to i Step 4 : fact = fact * i Step 5 : Decrement i by 1 Step 6: Repeat steps 46 until i > 0 Step 7 : Print fact Step 8 : Stop Program (fact.sh) # Factorial value using until echo -n "Enter a positive number : " read n f=1 until [ $n -lt 1 ] do f=`expr $f \* $n` n=`expr $n - 1` done echo "Factorial value : $f" Output [vijai@localhost loops]$ sh fact.sh Enter a positive number : 10 Factorial value : 3628800 2.4.GSum of 1..N natural numbers Algorithm Step 1 : Start Step 2 : Read n Step 3 : Initialize 0 to sum and 1 to i Step 4 : Add i to sum Step 5 : Increment i by 1 Step 6: Repeat steps 46 until i n Step 7 : Print sum Step 8 : Stop
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Program (sum1ton.sh) # Sum of 1+2+3+ ... +N numbers echo -n "Enter N value : " read n sum=0 i=1 until [ $i -gt $n ] do sum=`expr $sum + $i` i=`expr $i + 1`

done echo "The sum of n numbers is $sum" Output [vijai@localhost loops]$ sh sum1ton.sh Enter N value : 26 The sum of n numbers is 351 2.4.HData Statistics Algorithm Step 1 : Start Step 2 : Initialize 0 to pc, sum, i Step 3 : Read a number Step 4 : If number = 9999 then goto step 10 Step 5 : Increment i by 1 Step 6 : If number 0 then goto step 3 Step 7 : Increment pc by 1 Step 8 : Add number to sum Step 9 : Goto step 3 Step 10 : Compute avg = sum / pc Step 11 : Print i, pc, avg, Step 12 : Stop Program (datastat.sh) # Aggregate of positive nos using break and continue clear pc=0 s=0 i=0
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

until false do echo -n "Enter a number (9999 to quit) : " read n if [ $n -eq 9999 ] then break fi i=`expr $i + 1` if [ $n -le 0 ] then continue fi pc=`expr $pc + 1` s=`expr $s + $n` done avg=`expr "scale=2; $s / $pc" | bc` echo "Total No. of entries : $i" echo "No. of positive datas : $pc" echo "Positive aggregate : $avg" Output

[vijai@localhost loops]$ sh datastat.sh Enter a number (9999 to quit) : 32 Enter a number (9999 to quit) : 78 Enter a number (9999 to quit) : 0 Enter a number (9999 to quit) : 11 Enter a number (9999 to quit) : 47 Enter a number (9999 to quit) : -9 Enter a number (9999 to quit) : 12 Enter a number (9999 to quit) : 7 Enter a number (9999 to quit) : 9999 Total No. of entries : 8 No. of positive datas : 6 Positive aggregate : 31.16
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Ex. No: 2.5 COMMAND BASED SCRIPTS Aim To write shell scripts using shell commands. The shell's programming features coupled with the UNIX commands make it an extremely useful programming language. It is programming practice to tell the system that the file contents are set of commands to be interpreted by the specified shell in the first line as
#!/bin/bash

File Test operations The following are some of the options for test ( conditional) expressions that work with files. Condition Return value -e filename true if file exists -f filename true if file exists and is ordinary -d filename true if file exists and is directory -r filename true if file exists and is readable -w filename true if file exists and is writeable -x filename true if file exists and is executable -s filename true if file exists and is non-empty file1 -nt file2 true if file1 is newer than file2 Special Variables Shell posses certain special variables prefixed by a $ reserved for specific functions. These are also known as positional parameters. Some of them are Variable Description $0 Name of the script $n Command-line arguments ($1 for first, $2 for second argument, and so on) $# Number of arguments supplied to the script $? Exit status of the recent command Result Thus programming constructs using shell commands were executed
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.5.ATime based greeting Program (wish.sh) #!/bin/bash

x=`date +%H` mrd=`date +%P` if [ $mrd=='am' ] then if [ $x -le 11 ] then echo "Good Morning" fi else if [ $x -le 2 ] then echo "Good Afternoon" elif [ $x -le 6 ] then echo "Good Evening" else echo "Good Night" fi fi Output [vijai@localhost command]$ sh wish.sh Good Morning 2.5.BNumber of days in a month Program (monthdays.sh) # Number of days in a month mth=`date +%m` mn=`date +%B` case $mth in 02)echo "February usually has 28 days" echo "If leap year, then it has 29 days" ;; 04|06|09|11)echo "The current month $mn has 30 days" ;; *) echo "The current month $mn has 31 days" esac Output [vijai@localhost command]$ sh monthdays.sh The current month April has 30 days
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.5.CCommands menu Program (cmdmenu.sh) # Menu program ch='y' while [ $ch == 'y' ] do echo -e "\tMENU 1. List of files 2. Working Directory 3. Date and Time 4. Users of the system

5. Calendar Enter the option : \c" read choice case "$choice" in 1) ls -l ;; 2) pwd ;; 3) date ;; 4) who ;; 5) cal esac echo -n "Do you wish to continue (y/n) : " read ch done Output [vijai@localhost command]$ sh cmdmenu.sh MENU 1. List of files 2. Working Directory 3. Date and Time 4. Users of the system 5. Calendar Enter the option : 4 vijai pts/20 Apr 4 13:41 (linux-21.smkfomra.com) cse1 pts/13 Apr 4 13:43 (scl-58.smkfomra.com) Do you wish to continue (y/n) : n 2.5.DDirectory Listing Program (cmdmenu.sh) for x in . do ls -R $x done
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

Output [vijai@localhost command]$ sh list.sh .: list.sh shellscripts ./shellscripts: command decision loops patmatch simple ./shellscripts/command: cmdmenu.sh debug.sh dupremove.sh filetype.sh keystroke.sh ./shellscripts/decision: big3.sh emppay.sh grade.sh leap.sh oddeven.sh strcomp.sh ./shellscripts/loops: armstrong.sh datastat.sh fact.sh fibo.sh multable.sh ./shellscripts/patmatch: calc.sh rental.sh vote.sh vowel.sh ./shellscripts/simple: circle.sh degconv.sh simpint.sh swap.sh

2.5.EDetecting file type Program (filetype.sh) # File type echo -n "Enter filename : " read fname if [ -e $fname ] then if [ -f $fname ] then echo "Regular file" elif [ -d $fname ] then echo "Directory" else echo "Special file" fi else echo "File does not exist" fi Output [vijai@localhost command]$ sh filetype.sh Enter filename : samp.c Regular file
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.5.FDetecting user when logged on Program (logdetect.sh) #!/bin/bash #Detect the user at logon while true do if who|grep $1>/dev/null then echo $1 is logged in exit fi done Output [vijai@localhost command]$ sh logdetect.sh cse1 cse1 is logged in 2.5.GDuplicate file removal Program (dupremove.sh) # Duplicate file removal if cmp $1 $2 then echo "Files $1, $2 are identical" rm $2 echo "$2 file deleted" else

echo "Files $1, $2 are distinct" fi Output [vijai@localhost command]$ sh dupremove.sh samp.c s.c Files samp.c, s.c are identical s.c file deleted
Shell Programming 185253Computer Practice II cseannauniv.blogspot.com Vijai Anand

2.5.HCompilation and execution of a C program Program (debug.sh) # Compile and execute while true do gcc -o $1.out $1.c case "$?" in 0)echo "Executing ..." ./$1.out exit;; *) sleep 5 vi $1.c esac done Output [vijai@localhost command]$ sh debug.sh samp samp.c:4:10: warning: multi-line string literals are deprecated samp.c:4:10: missing terminating " character samp.c:4:10: possible start of unterminated string literal samp.c: In function `main': samp.c:4: parse error at end of input Executing ... Hello

You might also like