CP II Manual Final

144
UNIX commands for vi editor A text editor is one of the most common and useful tools in all Operating Systems. Unix provides a versatile editor vi, a full-screen editor and owes its origin to Bill Joy. "vi" stands for visual editor. A vi session begins by invoking vi with or without a filename $vi $vi filename vi functions in three modes namely: 1. Input mode—where any key depressed is entered as text 2. Command mode—where keys are used as commands to act on text (initial mode) 3. ex mode—ex mode commands that can be entered in the last line to act on text 1. INPUT MODE vi starts with command mode. To insert text any of the following commands should be used. Commands Function S. No. Command Description 1 $vi filename a full-screen editor will appear 2 i Inserts text to the left of the cursor. 3 I Inserts text at the beginning of line. 1

description

Manual Fina

Transcript of CP II Manual Final

Page 1: CP II Manual Final

UNIX commands for vi editor

A text editor is one of the most common and useful tools in all Operating Systems.

Unix provides a versatile editor vi, a full-screen editor and owes its origin to Bill Joy. "vi"

stands for visual editor. A vi session begins by invoking vi with or without a filename

$vi

$vi filename

vi functions in three modes namely:

1. Input mode—where any key depressed is entered as text

2. Command mode—where keys are used as commands to act on text (initial mode)

3. ex mode—ex mode commands that can be entered in the last line to act on text

1. INPUT MODE

vi starts with command mode. To insert text any of the following commands should be

used.

Commands Function

S.

No.

Command Description

1 $vi filename a full-screen editor will appear

2 i Inserts text to the left of the cursor.

3 I Inserts text at the beginning of line.

4 a Appends text to right of cursor

5 A Appends text at end of line

6 o Opens line below

7 O Opens line above

2. COMMAND MODEEDIT COMMANDS

Command Description

R Replaces more than a single character. The editor

displays REPLACE in the last line. The existing text

is overwritten as they are typed.

s Deletes a single character to the left and switches to

Input mode.

1

Page 2: CP II Manual Final

x Deletes the character in the current cursor position

?text Locates the text in the file. If not found, the message

"Pattern not found"appears. Use n to repeat the

forward search and N for backward search.

U or u Reverses the last change made to the buffer.

dd Cuts the entire line

dw Cuts the entire word

d$ Cuts a line from cursor position to the end of the line

d0 Cuts from the cursor position to the start of the line

yy Copies (yanks) the entire line

Yw Copies the entire word

p Pastes the text

NAVIGATION COMMANDS

Command Description

b Moves back to beginning of a word

w Moves forward to beginning of word

| Moves to start of the line

$ Moves to end of the line

k Up one line

j Down one line

h Left one character

l Right one character

Ctrl+f Scrolls a page forward

Ctrl+b Scrolls a page backward

lG To move to the specific line

2

Page 3: CP II Manual Final

3. EX MODE

The essential save and exit commands form the features of ex mode. Press :

(colon) in command mode to switch to ex mode. The : is displayed in the last line. Type

the command and press Enter key to execute the same.

Command Description

w

Saves file, displays the number of lines & characters and

returns to Input mode. If it is an unnamed file then vi puts a

message.

w file The file is saved under the given name

L1,L2 w file

Used to write specific line numbers to some file. The .

(dot) represents current line, 0 for first line and $ could be

used to represent last line.

q

Quits vi session and returns to $ prompt. vi has a safety

mechanism that warns if changes made to file are not

saved.

q!Quits vi session without saving any changes made since

the last save

:wq Save and exit

sh Escape to shell

%s/Sstr/Rstr/g

This is yet another powerful feature known as substitution.

It is similar to Find and Replace. % represents all lines, g

makes it global. To make vi ask for confirmation before

replacing use gc instead of g.

r file To insert another file into the current file.

new file Splits screen into multiple windows and opens the file.

3

Page 4: CP II Manual Final

4

Page 5: CP II Manual Final

C PROGRAMMING ON UNIX

5

Page 6: CP II Manual Final

6

Page 7: CP II Manual Final

Ex. No. 1.1 Date:

Nested Functions

AIM:

To write a C program to implement nested functions.

ALGORITHM:

1. Start the program.

2. Read x, y, z.

3. Call the function ratio ( ).

4. Function ratio( ), calls the function diff( ).

5. Display the return value.

6. Stop the program.

PROGRAM:

#include <stdio.h>

#include<stdio.h>

main()

{

int x,y,z;

float ratio(int,int,int);

printf("Enter x,y,z values......");

scanf("%d%d%d",&x,&y,&z);

printf("Ratio is..%f\n",ratio(x,y,z));

}

float ratio(int x,int y,int z)

{

int diff(int,int) ;

if(diff(y,z))

return((float)x/(y-z));

else

return(0);

}

diff(int m, int n)

{

if(m!=n) return(1);

else return(0);

}

7

Page 8: CP II Manual Final

OUTPUT:

[staff@localhost ~]$cc nested.c

[staff@localhost ~]$ ./a.out

Enter x,y,z values......4 6 8

Ratio is..-2.000000

RESULT:

Thus the C program to implement nested functions is written and executed.

SUPPLEMENTARY PROGRAMS:

1. Write a C program to find the sum and difference of two matrices using functions.

8

Page 9: CP II Manual Final

2. Write a C program to find the product of two matrices using functions.

9

Page 10: CP II Manual Final

Ex. No. 1.2 Date:

Reverse the String using Recursion

AIM:

To write a C program to reverse the given string using recursion.

ALGORITHM:

1. Start the program.

2. Read a string.

3. Call the function reverse ( ).

4. Function reverse () calls itself recursively.

5. Display the reversed string.

6. Stop the program.

PROGRAM:

#include<stdio.h>

main()

{

void reverse();

printf("Enter Line of Text...\n");

reverse();

printf("\n");

}

void reverse()

{ char c;

if((c=getchar( ))!='\n')

reverse();

putchar(c);

}

OUTPUT:

[staff@localhost ~]$cc reverse.c

[staff@localhost ~]$ ./a.out

Enter Line of Text...

hai welcome

emoclew iah

RESULT:

Thus the C program to inverse the given string is written and executed.

10

Page 11: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

1. Write a C program to print the factorial of a given number using recursion.

2. Write C program to generate following triangle. 1 1 2 3 1 2 3 4 5 1 2 3 4 5 6 7

11

Page 12: CP II Manual Final

Ex. No. 1.3 Date:

Towers of HanoiAIM:

To write a C program to implement Towers of Hanoi problem.

ALGORITHM:

1. Start the program.

2. Read the number of disks.

3. Call the function honoi ( )

4. Function honoi ( ) calls itself recursively to display the result.

5. Stop the program.

PROGRAM:

#include<stdio.h>

main()

{

void honoi (int, char, char, char);

int n;

printf ("How many disk..\n");

scanf ("%d", &n);

honoi (n, 'L', 'R', 'C');

}

void honoi (int n, char from, char to, char temp)

{

if(n>0)

{

honoi(n-1,from,temp,to);

printf("Move disk %d from %c to %c\n",n,from,to);

honoi(n-1,temp,to,from);

}

}

OUTPUT:

[staff@localhost ~]$ cc honoi.c

[staff@localhost ~]$ ./a.out

How many disk..

3

Move disk 1 from L to R

12

Page 13: CP II Manual Final

Move disk 2 from L to C

Move disk 1 from R to C

Move disk 3 from L to R

Move disk 1 from C to L

Move disk 2 from C to R

Move disk 1 from L to R

RESULT:

Thus the C program to implement Towers of Hanoi is written and executed.

SUPPLEMENTARY PROGRAM:

1. Write a C program to find the value of nCr using recursion.

13

Page 14: CP II Manual Final

Ex. No. 1.4 Date:

Menu Driven Calculator using FunctionsAIM:

To write a C program to implement menu driven calculator using functions.

ALGORITHM:

1. Start the program.

2. Display the options: (1.Add 2.Mul 3. Mod 4.Exit)

3. Choose the option

4. Read a and b

5. If option is Add, add a and b.

6. If option is Mul, multiply a and b.

7. If option is Mod, find remainder using a % b.

8. If option is Exit

Stop the program

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

int add(int a, int b);

int mul(int a, int b);

int mod(int a, int b);

main()

{

int a, b, ch;

float r;

system("clear");

while(1)

{

printf("\nMenu...\n");

printf("1-Addition\n2-Multiplication\n3-Modulus\n4-Exit\n");

printf("Enter Your Choice....");

scanf("%d",&ch);

printf("\n Enter a and b values...");

scanf("%d%d",&a,&b);

switch(ch)

{

14

Page 15: CP II Manual Final

case 1:

r=add(a,b);

printf("\n Sum of %d and %d is =%f",a,b,r);

break;

case 2:

r=mul(a,b);

printf("\n Product of %d and %d is =%f",a,b,r);

break;

case 3:

r=mod(a,b);

printf("\n Modulus of %d and %d is =%f",a,b,r);

break;

case 4:

exit(0);

}

}

}

int add(int a, int b)

{

int res;

res=a+b;

return(res);

}

int mul(int a, int b)

{

int res;

res=a*b;

return(res);

}

int mod(int a, int b)

{

int res;

res=a %b;

return(res);

}

15

Page 16: CP II Manual Final

OUTPUT:

[staff@localhost ~]$ cc menu.c

[staff@localhost ~]$ ./a.out

Menu...

1-Addition

2-Multiplication

3-Modulus

4-Exit

Enter Your Choice....1

Enter a and b values...3 4

Sum of 3 and 4 is =7.000000

Menu...

1-Addition

2-Multiplication

3-Modulus

4-Exit

Enter Your Choice....2

Enter a and b values...3 7

Product of 3 and 7 is =21.000000

Menu...

1-Addition

2-Multiplication

3-Modulus

4-Exit

Enter Your Choice....3

Enter a and b values...66 5

Modulus of 66 and 5 is =1.000000

Menu...

1-Addition

2-Multiplication

3-Modulus

4-Exit

Enter Your Choice....4

RESULT:

Thus the C program to implement menu driven calculator using functions is

written and executed.

16

Page 17: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Extend the above program to perform subtraction and division.

17

Page 18: CP II Manual Final

Ex. No. 1.5 Date:

Dynamic Memory Allocation

AIM:

To write a C program to concatenate two strings using dynamic memory

allocation.

ALGORITHM:

1. Start the program.

2. Initialize strings s1,s2,s3 with malloc() function.

3. Read s1,s2.

4. Copy s1 to s3.

5. Append s2 to s3.

6. Stop the program

PROGRAM:

#include<stdio.h>

#include<malloc.h>

#define length 30

main()

{

char *s1,*s2,*s3,c;

int i,k;

s1=(char *)malloc(length *sizeof (char));

s2=(char *)malloc(length *sizeof (char));

s3=(char *)malloc(2*length *sizeof (char));

printf("\n Enter the string1:");

scanf("%s",s1);

printf("\n Enter the string2:");

scanf("%s",s2);

i=0;

while((c=*(s1+i))!='\0')

{

s3[i]=c;

i++;

}

k=0;

while((c=*(s2+k))!='\0')18

Page 19: CP II Manual Final

{

s3[i+k]=c;

k++;

}

s3[i+k]='\0';

printf("\n concatenated string is %s\n",s3);

}

OUTPUT:

[staff@localhost ~]$ cc strcat.c

[staff@localhost ~]$ ./a.out

Enter the string1:hello

Enter the string2:welcome

concatenated string is hellowelcome

RESULT:

Thus the C program to concatenate two strings using dynamic memory allocation

is written and executed.

SUPPLEMENTARY PROGRAMS:

1. Write a C program for string copy using dynamic memory allocation.

19

Page 20: CP II Manual Final

2. Write a C program for string compare using dynamic memory allocation.

20

Page 21: CP II Manual Final

Ex. No. 1.6 Date:

Sorting Names using functions and PointersAIM:

To write a C program for sorting names using functions and pointers.

ALGORITHM:

1. Start the program.

2. Enter the value of n.

3. Allocate memory for each name using calloc ( ) and read n names.

4. Sort the names using sort ( ) function.

5. Display the sorted list of names.

6. Stop the program

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

void sort(char **name,int n);

main()

{

char * names[20];

char temp[20];

int n,i;

printf("\n HOW MANY ENTRIES \n");

scanf("%d",&n);

printf("\n ENTER THE %d NAMES ONE BY ONE \n",n);

for(i=0;i<n;i++)

{

names[i]=(char *) calloc(20,sizeof(char));

scanf("%s",names[i]);

}

sort(names,n);

printf("\n Names in Sorted form \n");

for(i=0; i<n;i++)

{

printf("%s",names[i]);

printf("\n");

21

Page 22: CP II Manual Final

}

}

void sort( char **name,int n)

{

int i,j,k;

char *temp;

temp=(char *) calloc(20,sizeof(char));

for(i=0;i<=n-2;i++)

for(j=i+1;j<=n-1;j++)

if(strcmp(name[i],name[j])> 0)

{

strcpy(temp,name[i]);

strcpy(name[i],name[j]);

strcpy(name[j],temp);

}

}

OUTPUT:

[staff@localhost ~]$ cc sort.c

[staff@localhost ~]$ ./a.out

HOW MANY ENTRIES

6

ENTER THE 6 NAMES ONE BY ONE

sri

vidya

arun

bala

neha

uma

Names in Sorted form

arun

bala

neha

sri

uma

vidya

22

Page 23: CP II Manual Final

RESULT:

Thus the C program to sort names using functions and pointers is written and

executed.

SUPPLEMENTARY PROGRAM:

1. Write a C program for sorting student record based on student name.

( Declare array of structures with only two members: name, mark. )

23

Page 24: CP II Manual Final

Ex. No. 1.7 Date:

Counting of Characters, Words and Lines in a FileAIM:

To write a C program to count the number of characters, words and lines in a file.

ALGORITHM:

1. Start the program.

2. Declare the file pointer ptr.

3. Open the file in read mode.

4. Read the contents of file character by character.

5. Check the character type and increment the counters accordingly.

6. Stop the program.

PROGRAM:

#include<stdio.h>

main()

{

int a=0,w=0,d=0,l=0,t=0;

char ch;

FILE *ptr;

ptr=fopen("inf.c","r");

while((ch=getc(ptr)) != EOF)

{

if(isalpha(ch)) a++;

if(isdigit(ch)) d++;

if(ch==' ' || ch=='\t') w++;

if(ch=='\n')

{

l++; w++;

}

}

printf("No. of characters are = %d\n",a);

printf("No. of words are = %d\n",w);

printf("No. of digits are = %d\n",d);

printf("No. of lines are = %d\n",l);

fclose(ptr);

}

24

Page 25: CP II Manual Final

OUTPUT:

[staff@localhost ~]$ cc count.c

[staff@localhost ~]$ ./a.out

No. of characters are = 48

No. of words are = 8

No. of digits are = 0

No. of lines are = 4

RESULT:

Thus the C program for counting of characters, words and lines in the file is

written and executed.

SUPPLEMENTARY PROGRAMS:

1. Write a C program to replace all the blank spaces in a file with ‘$’ symbol.

25

Page 26: CP II Manual Final

Ex. No. 1.8 Date:

File Copy using Command Line ArgumentsAIM:

To write a C program to copy the contents of one file to another file using

command line arguments.

ALGORITHM:

1. Start the program.

2. Execute the program with source file name and target file name as command

line arguments.

3. Declare the file pointers ptr1, ptr2.

4. Open the input file in read mode and output file in write mode.

5. Read the contents of input file and write into output file.

6. Stop the program.

PROGRAM:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

{

long int x;

int i=0;

char c,str[25];

FILE *ptr1, *ptr2;

ptr1=fopen(argv[2],"r");

ptr2=fopen(argv[3],"w");

printf("\nCommand line arguments: %s\t%s\n",argv[2],argv[3]);

printf("\nContents in infile: \n");

while ((c=getc(ptr1)) != EOF)

putchar(c);

rewind(ptr1);

while ((c=getc(ptr1)) !=EOF)

putc(c,ptr2);

fclose(ptr1);

fclose(ptr2);

printf("\n\nContents in outfile: \n");

26

Page 27: CP II Manual Final

ptr2=fopen(argv[3],"r");

while ((c=getc(ptr2)) != EOF)

putchar(c);

fclose(ptr2);

return 1;

}

OUTPUT:

[staff@localhost ~]$ cc filecopy.c

[staff@localhost ~]$ ./a.out filecopy infile.txt outfile.txt

Command line arguments: infile.txt outfile.txt

Contents in infile:

Hello! Welcome to KSRIET

Contents in outfile:

Hello! Welcome to KSRIET

RESULT:

Thus the C program for copying the contents of one file to another is written and

executed.

SUPPLEMENTARY PROGRAMS:

1. Write a C program to concatenate two files.

27

Page 28: CP II Manual Final

2. Write a C program to convert the contents of a file into uppercase.

28

Page 29: CP II Manual Final

Ex. No. 1.9 Date:

Sequential Access FileAIM:

To write a C program to process sequential access file.

ALGORITHM:

1. Start the program.

2. Declare a structure called student.

3. Declare the file pointer ptr.

4. Display the options: (1.Add 2.Delete 3. Display 4.Exit)

5. Choose the option

6. If option is Add

open the file in append mode

read one student details and append at the end of the file

7. If option is Delete

Read roll number to delete, search and find the record

Delete the record and move the remaining records accordingly

8. If option is Display

Display the details

9. If option is Exit

Stop the program

PROGRAM:

#include <stdio.h>

#include <stdlib.h>

void add();

void display();

void dele();

void modify();

void search();

struct student

{

int rno;

char name[20];

int age;

int marks;

}s;

29

Page 30: CP II Manual Final

FILE *ptr;

void main()

{

int ch;

ptr=fopen("stud.dat","wb");

while(1)

{

printf("\n1. Add");

printf("\n2. Delete");

printf("\n3. Display");

printf("\n4. Exit");

printf("\nEnter your option (1-4): ");

scanf("%d", &ch);

switch(ch)

{

case 1: add();

break;

case 2: dele();

break;

case 3: display();

break;

case 4: exit(0);

default:printf("\n\nInvalid option......\n");

break;

}

}

}

void add()

{

struct student s1;

ptr=fopen("stud.dat","a+");

while(fread(&s1,sizeof(s1),1,ptr));

printf("Roll No. :");

scanf("%d",&s1.rno);

printf("Name :");

scanf("%s",s1.name);

30

Page 31: CP II Manual Final

printf("Age :");

scanf("%d",&s1.age);

printf("Marks :");

scanf("%d",&s1.marks);

fwrite(&s1,sizeof(s1),1,ptr);

fclose(ptr);

}

void dele()

{

struct student s1;

int found=0,roll;

long offset;

ptr=fopen("stud.dat","r+t");

printf("Enter the Roll no. to delete :");

scanf("%d",&roll);

offset=ftell(ptr);

while (fread(&s1,sizeof(s1),1,ptr))

{

if (s1.rno==roll)

{ if ((fread(&s1,sizeof(s1),1,ptr)) !=NULL)

{

do {

fseek(ptr,offset,SEEK_SET);

fwrite(&s1,sizeof(s1),1,ptr);

offset=ftell(ptr);

fseek(ptr,sizeof(s1),SEEK_CUR);

} while(fread(&s1,sizeof(s1),1,ptr));

}

fseek(ptr,offset,SEEK_SET);

putc(NULL,ptr);

found=1;

break;

}

offset=ftell(ptr);

}

if (found==0)

31

Page 32: CP II Manual Final

printf("\n\n.............Record Not Found..........\n");

fclose(ptr);

}

void display()

{

struct student s1;

long offset;

ptr=fopen("stud.dat","r");

offset=ftell(ptr);

while(fread(&s1,sizeof(s1),1,ptr))

{ if (s1.rno!= 0)

{

printf("\n\nRoll No.: %d",s1.rno);

printf("\nName. : %s",s1.name);

printf("\nAge : %d",s1.age);

printf("\nMarks : %d",s1.marks);

printf("\n----------------------------------\n");

}

}

fclose(ptr);

}

OUTPUT:

[staff@localhost ~]$ cc student.c[staff@localhost ~]$ ./a.out1. Add2. Delete3. Display4. ExitEnter your option (1-6): 1Roll No. :1Name :ArunAge :20Marks :901. Add2. Delete3. Display4. ExitEnter your option (1-6): 1Roll No. :2

32

Page 33: CP II Manual Final

Name :AmuthaAge :25Marks :801. Add2. Delete3. Display4. ExitEnter your option (1-6): 3Roll No.: 1Name. : ArunAge : 20Marks : 90----------------------------------Roll No.: 2Name. : AmuthaAge : 25Marks : 80----------------------------------1. Add2. Delete3. Display4. ExitEnter your option (1-6): 2Enter the Roll no. to delete :11. Add2. Delete3. Display4. ExitEnter your option (1-6): 3Roll No.: 2Name. : AnithaAge : 23Marks : 85----------------------------------1. Add2. Delete3. Display4. ExitEnter your option (1-6):4

RESULT:

Thus the C program for sequential access file processing is written and executed.

33

Page 34: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Extend the above program to modify and search a particular record in a file.

(Hint: If option is Modify - 1. Read roll number to modify, search and find the record

2. Read the new details and modify the record with new details

If option is Search – 1. Read roll number to search, find and display the record)

34

Page 35: CP II Manual Final

Ex. No. 1.10 Date:

RANDOM ACCESS FILE

AIM:

To write a C program to process random access file.

ALGORITHM:

1. Start the program.

2. Declare the file pointer ptr.

3. Open a file in write mode.

4. Read a string and write in the file.

5. Close the file and open it in read mode.

6. Read and display the contents of the file

7. Use fseek ( ), rewind ( ) and ftell ( ) functions to move the file pointer to the

required location.

8. Stop the program.

PROGRAM:

#include <stdio.h>

#include <stdlib.h>

void main()

{

long int x;

int i=0;

char c, str[25];

FILE *ptr;

system("clear");

ptr=fopen("st.txt","w");

printf("Enter a string : \n");

while ((c=getchar()) != '\n')

putc(c,ptr);

fclose(ptr);

ptr=fopen("st.txt","r");

if (ptr != NULL)

{

printf("\n\nThe String stored in the file is : " );

while ((c=getc(ptr)) != EOF)

putchar(c);

35

Page 36: CP II Manual Final

//fseek() is used to move the file pointer to a desired location

fseek(ptr,0L,2);

//ftell() returns the current position of the file pointer

x=ftell(ptr);

printf("\nPtr is at the end of file => The size of File is : %ld\n",x);

//rewind() is used to move file pointer to the beginning of the file

rewind(ptr);

x=ftell(ptr);

printf("\n Ptr is at the begining of the file => The size of File is : %ld\n",x);

}

else

printf("\nThe file does not exists");

fclose(ptr);

}

OUTPUT:

[staff@localhost ~]$ cc random.c

[staff@localhost ~]$ ./a.out

Enter a string :

welcome

The String stored in the file is : welcome

Ptr is at the end of file => The size of File is : 7

Ptr is at the begining of the file => The size of File is : 0

RESULT:

Thus the C program for random access file processing is written and executed.

36

Page 37: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Extend the above program to move the file pointer to the beginning of the file

using fseek().

37

Page 38: CP II Manual Final

Ex. No. 1.11 Date:

Macro SubstitutionAIM:

To write a C program to perform macro substitution.

ALGORITHM:

1. Start the program.

2. Define the macros using #define statement

3. Read a number.

4. Call the macros by passing the parameter

5. Stop the program.

PROGRAM:

#include<stdio.h>

#define sq(n) (n*n)

#define cube(n) (n*n*n)

#include <stdio.h>

main()

{

int n,s,c;

printf("\nEnter a number : ");

scanf("%d",&n);

s=sq(n);

c=cube(n);

printf("\nSquare value of %d is %d\n",n,s);

printf("\nCube value of %d is %d\n",n,c);

}

OUTPUT:

[staff@localhost ~]$ ./a.out

Enter a number : 4

Square value of 4 is 16

Cube value of 4 is 64

RESULT:

Thus the C program for performing macro substitution is written and executed.

38

Page 39: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

1. Write a C program to define a macro for finding the largest of three numbers.

2. Write a C program to define a macro for displaying the given string.

39

Page 40: CP II Manual Final

40

Page 41: CP II Manual Final

UNIX COMMANDS

41

Page 42: CP II Manual Final

2.1 UNIX Commands

S. No.

Command Syntax Example Description

1 mkdir mkdir dirname [jagan@venkat ~]$ mkdir cse[jagan@venkat ~]$ ls cse

It creates a new directory

2 cd cd dirname [jagan@venkat ~]$ cd cse[jagan@venkat cse]$

It is used to change the current directory

3 cd\ cd\ [jagan@venkat student]$ cd\[jagan@venkat ~]$

It is used to exit the current directory.

4. rmdir rmdir dirname [jagan@venkat cse]$ dir student[jagan@venkat cse]$ rmdir student[jagan@venkat cse]$ dir

It is used to remove an empty directory.

5 pwd pwd [jagan@venkat cse]$ pwd /home/jagan/cse

It is used to display the current working directory

6 rm rm filename [jagan@venkat cse]$ ls f1 f2[jagan@venkat cse]$ rm f1 [jagan@venkat cse]$ ls f2

Remove the particular file in current directory

7 cat cat>filename…“ctrl+D”

[jagan@venkat cse]$ cat>f1[jagan@venkat cse]$ lsf1 f2

It is used to create a new file

8 cp cp source destination

[jagan@venkat cse]$ cp f1 f2[jagan@venkat cse]$ cat f2hello this sample file

copy the source file to the destination file

9 cat cat filename [jagan@venkat cse]$ cat f2ksriet at tiruchengode

It displays the content of the file

10 mv mv source destination

[jagan@venkat cse]$ mv f1 new1[jagan@venkat cse]$ lsf2 new1 se

Move source file to the destination files.

11 cmp cmp fn1,fn2 [jagan@venkat cse]$ cmp se seense seen differ: byte 1, line 1

It is used to compare two files

12 diff diff fn1,fn2 [senthil@prabhu ~]$ diff sen1 sen21c1

It is used to print the all the difference between the two files.

13 tail tail filename [senthil@prabhu cse]$ tail a2hello

Print last 10 line of the file

14 wc wc filename [jagan@venkat cse]$ wc se 2 5 26 se

It is used count lines,words and characters of a file

15 wc (i) wc -l filename [senthil@prabhu cse]$ wc -l a21 a2[senthil@prabhu cse]$ wc -c a2

Count number of lines of the file.

Count number of characters in a 42

Page 43: CP II Manual Final

(ii) wc -c filename

(iii)wc -w filename

6 a2[senthil@prabhu cse]$ wc -w a21 a2

file Count number of words in a file.

16 uname uname –a [jagan@venkat cse]$ uname -aLinux venkat 3.1.0-7.fc16.i686 #1 SMP Tue Nov 1 21:00:16 UTC 2011 i686 i686 i386 GNU/Linux

It is used to know about the operating system details

17 uname uname –s [jagan@venkat cse]$ uname -sLinux

It is used to know the name of the operating system.

18 uname uname –n [staff2@localhost ~]$ uname -nlocalhost.localdomain

It is used to know the name of the network node (host name).

19 uname uname –r [staff2@localhost ~]$ uname -r2.6.18-238.el5

It is used to know the release number of the operating system.

20 uname uname –v [staff2@localhost ~]$ uname -v#1 SMP Sun Dec 19 14:24:47 EST 2010

It is used to know the version of the operating system.

21 uname uname –m [staff2@localhost ~]$ uname -mi686

It is used to know the machine id

22 who who [jagan@venkat cse]$ whovenkat tty1 2012-01-23 09:29 jagan pts/0 2012-01-23 09:30 (192.168.56.1)

It is used to show who is logged onto system

23 whoami whoami [jagan@venkat cse]$ whoami jagan pts/0 2012-01-23 09:30 (192.168.56.1)

It is used to know who owns the shell

24 whois whois [staff2@localhost ~]$ whoisjwhois version 3.2.3,Copyright (C) 1999-2005 Free Software Foundation, Inc.This program is free software with ABSOLUTELY NO WARRANTY

It is used to know Internet user name directory service.

25 passwd passwd [jagan@venkat cse]$ passwdChanging password for user jagan.Changing password for jagan.(current) UNIX password:New password:Retype new password:passwd: all authentication tokens updated successfully.

It is used to change the current password.

26 mail mail user name [staff2@localhost ~]$ mail staff1Subject: helloCc: sample

It is used to write the message to another user

43

Page 44: CP II Manual Final

27 write write username [root@venkat ~]# write jagan hello

It is used to write the message to another user

28 cal cal monthyear [root@venkat ~]# cal 1 2012 January 2012 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

It is used to print the calendar of the current year or Entered year

29 echo echo text [root@venkat ~]# echo ksrietKsriet

It is used to display the printed text document

30 env env [root@venkat ~]# envPWD=/root JAVA_HOME=/usr/java/jdk1.7.0_02/bin/javaLANG=en_US.UTF-8

SELINUX_LEVEL_REQUESTED=HISTCONTROL=ignoredupsSHLVL=1HOME=/rootLOGNAME=rootSSH_CONNECTION=192.168.56.1 49857 192.168.56.101 22LESSOPEN=||/usr/bin/lesspipe.sh %s

It is used to display environment

31 time time [root@venkat ~]# time real 0m0.000s user 0m0.000s sys 0m0.000s

It is used to display the timing programs.

32 df df [root@venkat ~]# dfFilesystem 1K-blocks Used Available Use% Mounted onrootfs 6223416 2832848 3327348 46% / devtmpfs 533144 0 533144 0% /dev tmpfs 541372 0 541372 0% /dev/shm tmpfs 541372 40156 501216 8%

It summarizes free disk space

33 man man command name

[root@venkat ~]# man fileNAME file â determine file type

It is used to display the given command’s manual information.

44

Page 45: CP II Manual Final

SYNOPSISfile [-bchiklLNnprsvz0] [--apple] [--mime-encoding] [--mime-type][-e testname] [-F separator] [-f namefile] [-m magicfiles] file ...file -C [-m magicfiles]file [--help]

34 last last [root@venkat ~]# lastjagan pts/1 192.168.56.1 Mon Jan 23 10:03 still logged inroot pts/0 192.168.56.1 Mon Jan 23 10:03 still logged inreboot system boot 3.1.0-7.fc16.i68 Mon Jan 23 10:02 - 10:19 (00:17)

It indicates last login of users.

35 ps ps [root@venkat ~]# psPID TTY TIME CMD 877 pts/0 00:00:00 bash1122 pts/0 00:00:00 ps

It shows the process status.

36 find find file name or path name

[jagan@venkat cse]$ find f2f2

It is used to find whether the particular file name or path name is available or not.

37 w w [root@venkat ~]# w 10:24:28 up 21 min, 2 users, load average: 0.00, 0.02, 0.05USER TTY FROM LOGIN@ IDLE JCPU PCPU WHATroot pts/0 192.168.56.1 10:03 0.00s 0.24s 0.01s w jagan pts/1 192.168.56.1 10:03 22.00s 0.11s 0.11s –bash

It shows who is on system, What command each job is executing.

38 date date [root@venkat ~]# dateMon Jan 23 10:26:23 IST 2012

It shows date and time

39 id id [jagan@venkat cse]$ iduid=1001(jagan) gid=1002(jagan) groups=1002(jagan) context=unconfined_u:unconfed_r:unconfined_t:s0-s0:c0.c1023

It is used to show login name, a user –id and group -id

40 du du [staff2@localhost ~]$ du8 ./.mozilla/plugins8 ./.mozilla/extensions

It is used to summarize the disk space

45

Page 46: CP II Manual Final

24 ./.mozilla8 ./cse104 .

2.2 File Management Commands

1 cat > filename

cat>f1 [jagan@venkat cse]$ cat>f1[jagan@venkat cse]$ lsf1 f2

To create a file with some contents. To end typing press Ctrl+d. The > symbol means redirecting output to a file. (< for input)

2 cat filename cat f2 [jagan@venkat cse]$ cat f2ksriet at tiruchengode

Displays the file contents.

3 cat >> filename

cat>>f2 [jagan@venkat cse]$ cat>>f2welcomes u all[jagan@venkat cse]$ cat f2ksriet at tiruchengodewelcomes u all

Used to append contents to a file

4 cp –i src des

cp -i f2 f1 [jagan@venkat cse]$ cp -i f2 f1cp: overwrite `f1'? y[jagan@venkat cse]$ cat f1lshello this sample file

Warns the user prior to overwriting the destination file

5 mv old new mv f1 new1 [jagan@venkat cse]$ mv f1 new1[jagan@venkat cse]$ lsf2 new1 se

rename an existing file or directory. –i option can also be used

6 mv f1 f2 f3 dir

mv f2 new1 copied [jagan@venkat cse]$ lscopied f2 new1 se[jagan@venkat cse]$ mv f2 new1 copied[jagan@venkat copied]$ lsf2 new1

To move a group of files to a directory.

7 rm file rm new1 [jagan@venkat copied]$ lsf2 new1[jagan@venkat copied]$ rm new1[jagan@venkat copied]$ lsf2

Used to delete a file or group of files. –i option can also be used

8 rm * rm * [jagan@venkat copied]$ rm *[jagan@venkat copied]$ ls

To delete all the files in the directory.

9 rm –r * rm –r * [jagan@venkat cse]$ lscopied se[jagan@venkat cse]$ rm -i *rm: cannot remove `copied': Is a directoryrm: remove regular file `se'? n

Deletes all files and sub-directories

10 ls ls [jagan@venkat cse]$ lscopied se

Lists all files and subdirectories (blue colored) in sorted manner.

11 ls name ls se [jagan@venkat cse]$ ls sese

To check whether a file or directory exists.

12 ls name* ls se* [jagan@venkat cse]$ ls se*se seen

Short-hand notation to list out filenames of a specific pattern.

46

Page 47: CP II Manual Final

13 ls –a ls –a [jagan@venkat cse]$ ls -a. .. copied se seen

Lists all files including hidden files (files beginning with .)

14 ls –x dirname

ls -x [jagan@venkat cse]$ ls -xcopied se seen

To have specific listing of a directory.

15 ls –R [staff2@localhost ~]$ ls -R.:1.c cse f1./cse:f1 f2

Recursive listing of all files in the subdirectories

16 ls –l ls –l [jagan@venkat cse]$ ls -l total 12

drwxrwxr-x. 2 jagan jagan 4096 Jan 23 11:30 copied -rw-rw-r--. 1 jagan jagan 26 Jan 23 11:10 se -rw-rw-r--. 1 jagan jagan 3 Jan 23 11:36 seen

Long listing showing file access rights (read/write/execute-rwx for user/group/others-ugo).

17 cmp file1 file2

cmp se seen [jagan@venkat cse]$ cmp se seense seen differ: byte 1, line 1

Used to compare two files. Displays nothing if files are identical.

18 chmod perm file

chmod uo+x se [jagan@venkat cse]$ chmod uo+x se[jagan@venkat cse]$ ls -ltotal 12drwxrwxr-x. 2 jagan jagan 4096 Jan 23 11:30 copied-rwxrw-r-x. 1 jagan jagan 26 Jan 23 11:10 se-rw-rw-r--. 1 jagan jagan 3 Jan 23 11:36 seen

Changes permission for the specified file. (r=4, w=2, x=1) chmod 740 file sets all rights for user, read only for groups and no rights for others.

19 chmod perm file

chmod 740 seen [jagan@venkat cse]$ chmod 740 seen[jagan@venkat cse]$ ls -ltotal 12drwxrwxr-x. 2 jagan jagan 4096 Jan 23 11:30 copied-rwxrw-r-x. 1 jagan jagan 26 Jan 23 11:10 se-rwxr-----. 1 jagan jagan 3 Jan 23 11:36 seen

Changes permission for the specified file. (r=4, w=2, x=1) chmod 740 file sets all rights for user, read only for groups and no rights for others.

20 bc bc Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 45+21 66

Basic calculator. Press Ctrl+d to quit

2.3 grep command

47

Page 48: CP II Manual Final

A frequent requirement is to look for a pattern or expression in a file. UNIX

handles this feature through grep and egrep. grep uses an regular expression to display

lines that match and egrep enables searching for multiple patterns.

Command Description grep 'end of' demo Quotes mandatory for text containing spacegrep this demo* Search this in multiple filesgrep –c to demo Number of occurrence of the word to in the filegrep –n sequence demo Display line numbers along with matching linesgrep –v word demo Displays lines that does not contain the text wordgrep –l vim * Displays files containing text vimgrep –i WORD demo Search for text ignoring case differencesgrep '^[0-9]' demo Lines that start with a numbergrep '[0-9]$' demo Lines that end with a numberls -l | grep "^d" Display the subdirectory namesgrep –c "^$" demo Display count of blank lines in the file.grep "2....$" stud Display lines that ends in the range 20000–29999egrep "lower|UPPER" demo Display lines that match either lower or upperegrep "(previous|current) Display lines that match either previous word orword" demo current word

Examples: [vijai@localhost regexpr]$ grep this demothis line is the 1st lower case line in this file.Two lines above this line is empty.

[vijai@localhost regexpr]$ grep 'end of' demo1. e - go to the end of the current word.2. E - go to the end of the current WORD.

[vijai@localhost regexpr]$ grep -c to demo5

[vijai@localhost regexpr]$ grep -n sequence demo15:WORD - WORD consists of a sequence of non-blank characters16:Word - word consists of a sequence of letters, digits and underscores.

48

Page 49: CP II Manual Final

[vijai@localhost regexpr]$ grep -v word demoTHIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.this line is the 1st lower case line in this file.This Line Has All Its First Character Of The Word With Upper Case.Two lines above this line is empty.vim Word Navigation2. E - go to the end of the current WORD.4. B - go to the previous WORD.WORD - WORD consists of a sequence of non-blank characterstelnet 172.16.4.256

[vijai@localhost regexpr]$ grep -l vim *demo readme[vijai@localhost regexpr]$ grep -i WORD demoThis Line Has All Its First Character Of The Word With Upper Case.vim Word NavigationYou may want to do several navigation in relation to words, such as:1. e - go to the end of the current word.2. E - go to the end of the current WORD.3. b - go to the previous word.4. B - go to the previous WORD.WORD - WORD consists of a sequence of non-blank charactersWord - word consists of a sequence of letters, digits and underscores.

[vijai@localhost regexpr]$ grep '^[0-9]' demo1. e - go to the end of the current word.2. E - go to the end of the current WORD.3. b - go to the previous word.4. B - go to the previous WORD.

[vijai@localhost regexpr]$ grep '[0-9]$' demotelnet 172.16.4.256

[vijai@localhost vijai]$ ls -l | grep "^d"drwxrwxr-x 2 vijai vijai 4096 Apr 9 14:30 regexprdrwxrwxr-x 7 vijai vijai 4096 Apr 4 14:57 shellscripts

[vijai@localhost regexpr]$ grep -c "^$" demo5

[vijai@localhost regexpr]$ egrep "lower|UPPER" demoTHIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.this line is the 1st lower case line in this file.

[vijai@localhost regexpr]$ egrep "(previous|current) word" demo1. e - go to the end of the current word.3. b - go to the previous word.

2.4 filter command

Filters are the central commands of the UNIX tool kit. It acts on data file where

lines are records, fields delimited by a character not used by the data (mostly |, default is 49

Page 50: CP II Manual Final

white space). The output is a set of records and the input file is unaltered by these

commands.

S.No. Command Description

1. headhead stud

head -5 stud

head -1 stud | wc –c

Displays first 10 records by default

Displays first 10 records by default

Displays first 5 records

length of first record

2. Tailtail stud

tail -5 stud | tee last5

used to display the last few records (10 records by default)

Displays last 10 records by default

Last 5 records listed & stored in file last5 using tee

3. cut

cut –d \| -f 1,3,4 stud

cut –d \| -f 2-4 stud

paste –d \| list1 list2

used to extract specific fields. The d option specifies the

delimiter and f for specifying the field list. The c option may

be used if extraction is done character wise

Fields 1,3,4 listed

Fields 2,3,4 listed

merges two cut files list1 and list2

4. sort

sort stud

sort –t \| +2 stud

sort –c stud

sort –t \| +3 -4 +4

stud

sort -t \| -nr +4 stud

uniq stud

reorders the file as per ASCII sequence. The t option is used

to specify delimiter

Sorted on 1st column by default

Sort as per 3rd column

Check if file is sorted using c option

Sorting on secondary keys

Sort on numeric field using n option, r for reverse

Display unique entries in a sorted file

5. nl

nl –s "|" stud

display file content with lines numbered. The s option is used

to specify separator

Displays entries numbered with separator |

6. tr

tr '[a-z]' '[A-Z]' <

stud

translates characters. Can be used to change text case. It

works with standard input <

Changes text to upper case

50

Page 51: CP II Manual Final

SHELL PROGRAMMING

51

Page 52: CP II Manual Final

52

Page 53: CP II Manual Final

Ex. No. 3.1 Date:

Maximum of Three Numbers

AIM:

To find the maximum among three numbers using shell programming.

ALGORITHM:

1. Start the program.

2. Read the three values as a,b,c.

3.1 Check if a is greater than b and c; if yes print a as maximum;

3.2 else check if b is greater than c ; if yes print b as maximum;

otherwise print c as maximum

4. Stop the program

PROGRAM:

#Maximum of three numbersecho "Enter value for A, B and C"

read a b c

if test $a -gt $b -a $a -gt $c

then

echo "$a is maximum number"

elif test $b -gt $c

then

echo "$b is maximum number"

else

echo "$c is maximum number"

fi

OUTPUT:

[staff@localhost ~]$ sh large

Enter value for A, B and C

12 45 23

45 is maximum number

RESULT:

Thus the Shell program for finding the maximum among three numbers has been

executed successfully.

53

Page 54: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

1. Write a shell script to find the minimum of three numbers.

2. Write a shell script to read a number and find its square and cube.

54

Page 55: CP II Manual Final

Ex. No. 3.2 Date:

Temperature ConversionAIM:

To convert the given Fahrenheit temperature to Celsius value using shell

programming.

ALGORITHM:

1. Start the program.

2. Read the Fahrenheit temperature value F.

3. Convert to Celsius value using the formula given below:

C= (F-32) *5/9

4. Print the Celsius temperature value.

5. Stop the program

PROGRAM:

# Fahrenheit to Celsius Conversion

echo "Enter F Value"

read f

echo $f

# real arithmetic is done using bc – basic calculator along with the scale function in echo

command

c=`expr "scale=2; ( $f - 32 ) * 5 / 9" | bc `

#c=`expr $c \* 5 / 9`

echo "Celsius Value = $c"

OUTPUT:

[staff@localhost ~]$ sh p22

Enter F Value

70

70

Celsius Value = 21.11

RESULT:

Thus the shell program for converting the given Fahrenheit temperature to Celsius has been executed successfully.

55

Page 56: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

1. Write a shell script to find area of a circle.

2. Write a shell script to find the simple interest.

56

Page 57: CP II Manual Final

Ex. No. 3.3 Date:

Finding Positive , Negative or ZeroAIM:

To check whether the given number is positive, negative or zero using shell

programming.

ALGORITHM:

1. Start the program.

2. Read a number n.

3. Check whether n is greater than zero; if yes print n is positive; otherwise check

n is less than zero; if yes print n is negative ; otherwise print n is zero

4. Stop the program

PROGRAM:

# Checking whether a given number is positive , negative or zero

echo "Enter a Number"

read n

if [ $n -gt 0 ]

then

echo "$n is positive"

elif [ $n -lt 0 ]

then

echo "$n is negative"

else

echo "$n is Zero"

fi

OUTPUT:

[staff@localhost ~]$ sh p24

Enter a Number

-12

-12 is negative

RESULT:

Thus the Shell program for checking whether the given number is positive,

negative or zero has been executed successfully.

57

Page 58: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

1. Write a shell script to check whether the given number is divisible by 4 and 7.

2. Write a shell script to check whether the given year is leap year or not.

58

Page 59: CP II Manual Final

Ex. No. 3.4 Date:

Display the Owner of the FileAIM:

To read a filename from the user and to display the owner of the file using shell

programming.

ALGORITHM:

1. Start the program.

2. Read the file name.

3. Use ls –l command to list all the files in the directory in detail form and store

the output in a temporary file.

4. Use grep command to look for the filename in the list.

5. Use tr command to remove the additional blank spaces and cut command to

extract the third field which is the owner of the file.

6. Print the owner name.

7. Stop the program

PROGRAM:

# to read a filename from the user and to display the owner of the file

echo “Enter a file name”

read name

ls -l > tmp

if(grep $name tmp > tmp1)

then

# tr -s , --squeeze-repeats replace each input sequence of a repeated character

# with a single occurrence of that character

# cut -Prints selected parts of lines from each FILE to standard output.

# cut -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter

# cut -f, --fields=LIST select only these fields; f3 - third field

line=`cat tmp1|tr -s " "|cut -d" " -f3`

ficheck=`echo $line |wc -c`echo " line = $line"echo "check= $check"if test $check -gt 1thenecho " the owner of the file $name is $line"else

59

Page 60: CP II Manual Final

echo "The file $name does not exist"fiOUTPUT:

[staff@localhost ~]$ sh p444

Enter a file name

file1.txt

line = staff

check= 6

the owner of the file file1.txt is staff

RESULT:

Thus the Shell program for reading a filename from the user and to display the

owner of the file has been executed successfully.

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to read a filename from the user and to display the file permission

of the file.

60

Page 61: CP II Manual Final

Ex. No. 3.5 Date:

Displaying FilenamesAIM:

To read an alphabet from the user and to display the filenames starting with the

input using shell programming.

ALGORITHM:

1. Start the program.

2. Read an alphabet ch.

3. Use find –name command along with the read character and print the output to

a file.

4. Check whether the file size is greater than zero using –s command; if so print

the filenames using cat command.

5. Stop the program

PROGRAM:

# to display all filenames starting with the user input alphabet in the current directory

echo " Enter an alphabet :"

read ch

find -name "$ch*" -print > tmp

if [ -s tmp ]

then

echo " The files starting with $ch are "

cat tmp

else

echo "There are no files starting with the $ch"

fi

rm tmp

OUTPUT

[staff@localhost ~]$ sh p446

Enter an alphabet :

t

The files starting with t are

./temp.c

61

Page 62: CP II Manual Final

./text

./t

./temp

./tmp1

./tmp

RESULT:

Thus the Shell program for reading an alphabet from the user to display the

filenames starting with the input alphabet has been executed successfully.

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to read a file name from the user and assign read, write and

execute permissions for that particular file.

62

Page 63: CP II Manual Final

Ex. No. 3.6 Date:

Employee Salary DetailsAIM:

To calculate the employee HRA details using shell programming.

ALGORITHM:

1. Start the program.

2. Enter the employee basic salary.

3. Calculate DA as 10% of basic pay.

4. Use conditions to calculate the HRA based on the basic pay.

5. Add DA and HRA to the basic and print the result.

6. Stop the program.

PROGRAM:

# Employee Salary Details

echo " Enter the employee basic salary "

read bs

da=`expr $bs \* 10 / 100`

echo "DA= $da"

if [ $bs -gt 5000 ]

then

hra=`expr $bs / 5`

echo "HRA = $hra"

elif [ $bs -ge 4000 -a $bs -le 5000 ]

then

hra=`expr $bs / 7`

echo "HRA = $hra"

else

hra=`expr $bs / 10`

echo "HRA = $hra"

fi

gross=`expr $bs + $da + $hra`

echo "Gross salary = $gross"

63

Page 64: CP II Manual Final

OUTPUT:

[staff@localhost ~]$ sh p26

Enter the employee basic salary

7000

DA= 700

HRA = 1400

Gross salary = 9100

RESULT:

Thus the Shell program for calculating employee salary has been executed

successfully.

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to prepare a grocery bill for 4 items.

64

Page 65: CP II Manual Final

Ex. No. 3.7 Date:

Sum of Even numbers

AIM:

To sum the even numbers using shell conditional statement programming.

ALGORITHM:

1. Start the program.

2. Enter the limit. Initialize sum as zero.

3. Use conditional statement to generate a loop until the limit. Generate the next

even number. Add it to the sum.

4. Print the sum.

5. Stop the program.

PROGRAM:

echo "Enter the Value for n"

read n

i=2

s=0

while [ $i -lt $n ]

do

s=`expr $s + $i`

i=`expr $i + 2`

done

echo "Sum of even numbers up to $n is $s"

OUTPUT:

[staff@localhost ~]$ sh p25

Enter the Value for n

20

Sum of even numbers up to 20 is 90

RESULT:

Thus the Shell program to sum the even numbers has been executed successfully.

65

Page 66: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to generate Fibonacci series.

66

Page 67: CP II Manual Final

Ex. No. 3.8 Date:

Sum of the Digits of a Number

AIM:

To sum the digits of a given numbers using shell programming.

ALGORITHM:

1. Start the program.

2. Read a number n. Set sum as zero.

3. Use conditional statements to generate a loop till the number becomes less than

1. Extract LSD of the number. Add it to the sum.

4. Print the sum.

5. Stop the program.

PROGRAM:

# Sum of Digits of a Number

echo " Enter the number: "

read n

temp=$n

sum=0

while [ $n -gt 0 ]

do

a=`expr $n % 10`

sum=`expr $sum + $a`

n=`expr $n / 10`

done

echo "Number typed is $temp and the sum of the digits is $sum"

OUTPUT:

[staff@localhost ~]$ sh p28

Enter the number:

43652

Number typed is 43652 and the sum of the digits is 20

RESULT:

Thus the Shell program to sum the digits of a given number has been executed

successfully.

67

Page 68: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to reverse the given number.

68

Page 69: CP II Manual Final

Ex. No. 3.9 Date:

Factorial of a Number

AIM:

To find the factorial of a number using shell programming.

ALGORITHM:

1. Start the program.

2. Read a number.

3. Use looping statement to calculate the factorial value.

4. Print the factorial number.

5. Stop the program.

PROGRAM:

# Factorial of a Number

echo " Enter the number: "

read n

i=1

f=1

while [ $i -le $n ]

do

f=`expr $f \* $i`

i=`expr $i + 1`

done

echo "The factorial of given number $n is $f"

OUTPUT:

[staff@localhost ~]$ sh p27

Enter the number:

7

The factorial of given number 7 is 5040

RESULT:

Thus the Shell program to find the factorial of a given number has been executed

successfully.

69

Page 70: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to read n numbers and find their sum.

70

Page 71: CP II Manual Final

Ex. No. 3.10 Date:

String CopyAIM:

To copy the given string to another string using shell programming.

ALGORITHM:

1. Start the program.

2. Read a string.

3. Calculate the length of the string using wc –c command

4. Use conditional statement to generate a loop till the length of the string. Extract

a character using cut –c command and append that character to the target

string.

5. Print the target string.

6. Stop the program.

PROGRAM:

# String Copy

echo " Enter the string : "

read s1

# wc -c counts the number of characters in a string

l=`echo $s1 | wc -c`

i=1

while [ $i -le $l ]

do

# cut -c removes ith character in the string

es2=`echo $s1 | cut -c $i`

i=`expr $i + 1`

cs3=`echo $cs3$es2`

done

echo " The actual string is $s1"

echo " The Copied string is $cs3"

OUTPUT:

[staff@localhost ~]$ sh p215

Enter the string :

welcome

The actual string is welcome

The Copied string is welcome

71

Page 72: CP II Manual Final

RESULT:

Thus the Shell program to copy one string to another string has been executed

successfully.

SUPPLEMENTARY PROGRAMS:

1. Write a Shell script to compare two strings. ( hint use = operator ).

2. Write a Shell script to find the length of the given string.

72

Page 73: CP II Manual Final

Ex. No. 3.11 Date:

Menu driven CalculatorAIM:

To develop a menu driven calculator using shell programming.

ALGORITHM:

1. Start the program.

2. Display the options. Read choice.

3. Use case statement to find the entered choice. Perform the operations based on

the choice.

5. Print the result.

4. Stop the program.

PROGRAM:

#Illustrate the use of the CASE statement

while true

do

echo " Menu"

echo "1. Addition"

echo "2. Subtraction"

echo "3. Multiplication"

echo "4. Division"

echo "5. Modulus"

echo "6. Quit"

echo -n "Enter your Choice"

read ch

case $ch in

1) read a b

c=`expr $a + $b`

echo $c;;

2) read a b

c=`expr $a - $b`

echo $c;;

3) read a b

c=`expr $a \* $b`

echo $c;;

4) read a b

73

Page 74: CP II Manual Final

c=`expr $a / $b`

echo $c;;

5) read a b

c=`expr $a % $b`

echo $c;;

6) break;;

*) echo "Invalid Choice"

esac

done

OUTPUT

[staff@localhost ~]$ sh p22

Menu

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Modulus

6. Quit

Enter your Choice1

10 20

30

Menu

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Modulus

6. Quit

Enter your Choice2

45 23

22

RESULT:

Thus the Shell program to develop a menu driven calculator has been executed

successfully.

74

Page 75: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to develop a menu driven program to execute any 5 UNIX

commands.

75

Page 76: CP II Manual Final

Ex. No. 3.12 Date:

Power FunctionAIM:

To write a shell program to perform power function.

ALGORITHM:

1. Start the program.

2. Read x and n

3. Initialize i=1, prod=1.

4. Assign prod= prod * x.

5. Increment i by 1.

6. Repeat step 4 & step 5 until i<=n.

7. Display prod

8. Stop the program.

PROGRAM:

echo Enter the number

read x

echo Enter the power

read n

i=1

prod=1

while [ $i -le $n ]

do

prod=`expr $prod \* $x`

i=`expr $i + 1`

done

echo $x raised to $n = $prod

OUTPUT:

[staff@localhost ~]$ sh power

Enter the number

3

Enter the power

3

3 raised to 3 = 27

RESULT:

Thus the shell program for performing the power function is written and executed.76

Page 77: CP II Manual Final

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to find the number of ordinary files and directories in the current

directory. ( hint: use ls –l | grep –c “^d” command for directory count )

77

Page 78: CP II Manual Final

Ex. No. 3.13 Date:

Prime Number GenerationAIM:

To write a shell program to print the prime numbers from 1 to 30.

ALGORITHM:

1. Start the program.

2. Initialize i=2, n=2.

3. Set loop for n<30.

4. Set loop for i<=n-1.

5. If n%i = 0 then goto step 7; Otherwise goto step 5.

6. Increment i and goto step 4.

7. If n=i then print n.

8. Increment n and goto step 3.

9. Stop the program.

PROGRAM:

n=2

echo $n

while [ $n -le 30 ]

do

i=2

while [ $i -le `expr $n - 1` ]

do

if [ `expr $n % $i` -eq 0 ]

then

break

else

i=`expr $i + 1`

fi

done

if [ $n -eq $i ]

then

echo $n

fi

n=`expr $n + 1`

done

78

Page 79: CP II Manual Final

OUTPUT:

2

3

5

7

11

13

17

19

23

29

RESULT:

Thus the shell program for printing prime numbers from 1 to 30 is written and

executed.

SUPPLEMENTARY PROGRAM:

1. Write a Shell script to check whether the given number is Armstrong number or not.

79

Page 80: CP II Manual Final

Ex. No. 3.14 Date:

Combinations of DigitsAIM:

To write a shell program to print all combinations of 1, 2 and 3.

ALGORITHM:

1. Start the program.

2. Set a for loop for i=1to 3.

3. Set a for loop for j1to 3.

4. Set a for loop for k=1to 3.

5. Display i, j and k

6. Stop the program.

PROGRAM:

clear

for i in 1 2 3

do

for j in 1 2 3

do

for k in 1 2 3

do

echo $i $j $k

done

done

done

OUTPUT:

1 1 1

1 1 2

1 1 3

1 2 1

1 2 2

1 2 3

1 3 1

1 3 2

1 3 3

2 1 1

2 1 2

80

Page 81: CP II Manual Final

2 1 3

2 2 1

2 2 2

2 2 3

2 3 1

2 3 2

2 3 3

3 1 1

3 1 2

3 1 3

3 2 1

3 2 2

3 2 3

3 3 1

3 3 2

3 3 3

RESULT:

Thus the shell program to print all combinations of 1,2 and 3 is written and

executed.

SUPPLEMENTARY PROGRAM:

1. Write a shell script to count the number of digits in the given number.

81

Page 82: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

C PROGRAMMING ON UNIX

82

Page 83: CP II Manual Final

1. Write a C program to find the sum and difference of two matrices using functions.

#include<stdio.h>

int a[10][10], b[10][10], c[10][10],d[10][10],p,q,m,n;

void readmatrix(int [10][10]);

void add(int [10][10], int [10][10]);

void sub(int [10][10], int [10][10]);

void display(int [10][10]);

int main()

{

int i,j,k;

printf("Enter the size of A matrix:");

scanf("%d%d",&p,&q);

printf("Enter the size of B matrix:");

scanf("%d%d",&m,&n);

if(p==m && q==n)

{

printf("Enter the elements of A matrix \n");

readmatrix(a);

printf("Enter the elements of B matrix \n");

readmatrix(b);

add(a,b);

sub(a,b);

}

else

printf("\nMatrices cannot be added due to size mismatch..\n");

printf("Addition of A and B matrix \n");

display(c);

printf("Subtraction of A and B matrix \n");

display(d);

return 1;

}

void readmatrix(int x[10][10])

{

int i,j;

for(i=0;i<p;i++)

for(j=0;j<q;j++)

83

Page 84: CP II Manual Final

scanf("%d",&x[i][j]);

}

void add(int a[10][10],int b[10][10])

{

int i,j;

for(i=0;i<p;i++)

for(j=0;j<q;j++)

c[i][j]=a[i][j]+b[i][j];

}

void sub(int a[10][10],int b[10][10])

{

int i,j;

for(i=0;i<p;i++)

for(j=0;j<q;j++)

d[i][j]=a[i][j]-b[i][j];

}

void display( int x[10][10])

{

int i,j;

for(i=0;i<p;i++)

{ for(j=0;j<q;j++)

printf("%5d",x[i][j]);

printf("\n");

}

}

OUTPUT:

[staff@localhost ~]$ cc matadd.c

[staff@localhost ~]$ ./a.out

Enter the size of A matrix:3 3

Enter the size of B matrix:3 3

Enter the elements of A matrix

4 4 4

4 4 4

4 4 4

Enter the elements of B matrix

84

Page 85: CP II Manual Final

2 2 2

2 2 2

2 2 2

Addition of A and B matrix

6 6 6

6 6 6

6 6 6

Subtraction of A and B matrix

2 2 2

2 2 2

2 2 2

***************************************************************

2. Write a C program to find the product of two matrices using functions.

#include<stdio.h>

int a[10][10], b[10][10], c[10][10],p,q,m,n;

void readmatrix(int [10][10]);

void mul(int [10][10], int [10][10]);

void display(int [10][10]);

int main()

{

int i,j,k;

printf("Enter the size of A matrix:");

scanf("%d%d",&p,&q);

printf("Enter the size of B matrix:");

scanf("%d%d",&m,&n);

if(q==m)

{

printf("Enter the elements of A matrix \n");

readmatrix(a);

printf("Enter the elements of B matrix \n");

readmatrix(b);

mul(a,b);

}

else

printf("\nMatrices cannot be multiplied....\n");

printf("Multiplication of A and B matrix \n");

85

Page 86: CP II Manual Final

display(c);

return 1;

}

void readmatrix(int x[10][10])

{

int i,j;

for(i=0;i<p;i++)

for(j=0;j<q;j++)

scanf("%d",&x[i][j]);

}

void mul(int a[10][10],int b[10][10])

{

int i,j,k;

for(i=0;i<p;i++)

for(j=0;j<q;j++)

for(k=0;k<q;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}

void display( int x[10][10])

{

int i,j;

for(i=0;i<p;i++)

{ for(j=0;j<q;j++)

printf("%5d",x[i][j]);

printf("\n");

}

}

OUTPUT:

[staff@localhost ~]$ cc matmul.c

[staff@localhost ~]$ ./a.out

Enter the size of A matrix:3 3

Enter the size of B matrix:3 3

Enter the elements of A matrix

1 1 1

1 1 1

1 1 1

86

Page 87: CP II Manual Final

Enter the elements of B matrix

1 1 1

1 1 1

1 1 1

Multiplication of A and B matrix

3 3 3

3 3 3

3 3 3

**********************************************************************

3. Write a C program to print the factorial of a given number using recursion.

#include<stdio.h>

long fact(int);

int main()

{

long f;

int n;

printf("\nEnter a number :");

scanf("%d",&n);

f = fact(n);

printf("The factorial of %d is %ld\n",n,f);

return 1;

}

long fact(int n)

{

if((n==1)||(n==0))

return (1);

else

return (n*fact(n-1));

}

OUTPUT:

[staff@localhost ~]$ cc fact.c

[staff@localhost ~]$ ./a.out

Enter a number :5

The factorial of 5 is 120

************************************************************************

87

Page 88: CP II Manual Final

4. Write C program to generate following triangle.

1

1 2 3

1 2 3 4 5

1 2 3 4 5 6 7

#include<stdio.h>

int main()

{ int i,j,k,l,n;

printf("Type N-no of lines in triangle:");

scanf("%d",&n);

l=1;

for(i=1,j=n-i;i<=n;i++,j--)

{

for(k=1;k<=j;k++)

printf(" ");

for(k=1;k<=l;k++)

printf("%5d",k);

printf("\n");

l+=2;

}

return 1;

}

[staff@localhost ~]$ ./a.out

Type N-no of lines in triangle:3

1

123

12345

***********************************************************************

5. Write a C program to find the value of nCr using recursion.

#include<stdio.h>

float combi(float,float);

int main()

{

float n,r;

printf("enter the value of n\n");

88

Page 89: CP II Manual Final

scanf("%f",&n);

printf("enter the value of r\n");

scanf("%f",&r);

printf("the result of (%f,%f) is %f\n",n,r,combi(n,r));

return 1;

}

float combi(float n,float r)

{

if((n==0) || (r==0))

return(1);

else

return((n/r)*combi(n-1,r-1));

}

OUTPUT:

[staff@localhost ~]$ cc ncr.c

[staff@localhost ~]$ ./a.out

enter the value of n

5

enter the value of r

3

the result of (5.000000,3.000000) is 10.000000

***************************************************************

6. Write a C program for string copy using dynamic memory allocation.

#include<stdio.h>

#include<malloc.h>

#define length 26

main()

{

char *s1,*s2,*s3,c;

int i,k;

s1=(char *)malloc(length *sizeof (char));

s2=(char *)malloc(length *sizeof (char));

printf("\n Enter the string1:");

scanf("%s",s1);

i=0;

while((c=*(s1+i))!='\0')

89

Page 90: CP II Manual Final

{

s2[i]=c;

i++;

}

s2[i]='\0';

printf("\n copied string is %s\n",s2);

}

OUTPUT:

[staff@localhost ~]$ cc strcpy.c

[staff@localhost ~]$ ./a.out

Enter the string1:Hello

copied string is Hello

***************************************************************

7. Write a C program for string compare using dynamic memory allocation.

#include<stdio.h>

#include<malloc.h>

#define length 26

int main()

{

char *s1,*s2,c;

int i,k;

s1=(char *)malloc(length *sizeof (char));

s2=(char *)malloc(length *sizeof (char));

printf("\n Enter the string1:");

scanf("%s",s1);

printf("\n Enter the string2:");

scanf("%s",s2);

i=0;

while(*(s1+i)== *(s2+i)&& (*(s1+i)!='\0'&& *(s2+i)!='\0'))

i++;

if (*(s1+i)=='\0'&& *(s2+i)=='\0')

printf("\nThe two strings are equal\n");

else

printf("\nThe two strings are not equal\n");

return 1;

}

90

Page 91: CP II Manual Final

OUTPUT:

[staff@localhost ~]$ cc strcmp1.c

[staff@localhost ~]$ ./a.out

Enter the string1:hai

Enter the string2:hai

The two strings are equal

***************************************************************

8. Write a C program for sorting student record based on student name.

( Declare array of structures with only two members: name, mark. )

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct student

{

char name[25];

int marks;

} *s;

void sort(struct student s1[ ], int n);

int main()

{

char temp[30];

int n,i;

printf("\n HOW MANY ENTRIES \n");

scanf("%d",&n);

printf("\n ENTER THE %d NAMES and marks ONE BY ONE \n",n);

s=(struct student *) calloc(n,sizeof(struct student ));

for(i=0;i<n;i++)

scanf("%s %d",(s+i)->name,&(s+i)->marks);

sort(s,n);

printf("\n Student Record in Sorted form \n");

for(i=0; i<n;i++)

{

printf("%s\t%d",(s+i)->name,(s+i)->marks);

printf("\n");

91

Page 92: CP II Manual Final

}

}

void sort( struct student s1[],int n)

{

int i,j,k;

struct student temp;

for(i=0;i<=n-2;i++)

for(j=i+1;j<=n-1;j++)

if(strcmp((s1+i)->name,(s1+j)->name)> 0)

{

temp=s1[i];

s1[i] =s1[j];

s1[j]=temp;

}

}

OUTPUT:

HOW MANY ENTRIES

3

ENTER THE 3 NAMES and marks ONE BY ONE

raja 90

kumar 70

kalai 70

Student Record in Sorted form

kalai 70

kumar 70

raja 90

***************************************************************

9. Write a C program to replace all the blank spaces in a file with ‘$’ symbol.

#include<stdio.h>

main()

{ int a=0,w=0,d=0,l=0,t=0; char ch;

FILE *ptr1,*ptr2;

ptr1=fopen("inf.c","r");

ptr2=fopen("outf.c","w");

while((ch=getc(ptr1)) != EOF)

92

Page 93: CP II Manual Final

{ if (ch!=' '&& ch!='\t')

putc(ch,ptr2);

else putc('$',ptr2);

}

fclose(ptr1); fclose(ptr2);

}

OUTPUT:

[staff@localhost ~]$ cc p310.c

[staff@localhost ~]$ ./a.out

[staff@localhost ~]$ cat outf.c

$wel$come

hello$hai

hai$hello

***************************************************************

10. Write a C program to concatenate two files.

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[])

{

long int x;

int i=0;

char c,str[25];

FILE *ptr1, *ptr2,*ptr3;

ptr1=fopen(argv[2],"r");

ptr2=fopen(argv[3],"r");

ptr3=fopen(argv[4],"w");

while ((c=getc(ptr1)) !=EOF)

putc(c,ptr3);

while ((c=getc(ptr2)) != EOF)

putc(c,ptr3);

fclose(ptr1);

fclose(ptr2);

fclose(ptr3);

printf("\n\nContents in concatenated file: \n");

ptr3=fopen(argv[4],"r");

while ((c=getc(ptr3)) != EOF)

93

Page 94: CP II Manual Final

putchar(c);

fclose(ptr3);

return 1;

}

OUTPUT:

[staff@localhost ~]$ ./a.out filecat.c file1.c file2.c file3.c

Contents in concatenated file:

Hello

Welcome

To

KSRIET

***************************************************************

11. Write a C program to convert the contents of a file into uppercase.

#include<stdio.h>

main()

{

char ch;

FILE *ptr1,*ptr2;

ptr1=fopen("inf.c","r");

ptr2=fopen("outf.c","w");

while((ch=getc(ptr1)) != EOF)

{

if (isalpha(ch))

putc(toupper(ch),ptr2);

else

putc(ch,ptr2);

}

fclose(ptr1);

fclose(ptr2);

}

OUTPUT:

[staff@localhost ~]$ cat inf.c

wel come

hello hai

hai hello

[staff@localhost ~]$ cc upper.c

94

Page 95: CP II Manual Final

[staff@localhost ~]$ ./a.out

[staff@localhost ~]$ cat outf.c

WEL COME

HELLO HAI

HAI HELLO

***************************************************************

12. Extend the above program to modify and search a particular record in a file.

void modify()

{

struct student s1;

int found=0,roll;

long offset;

ptr=fopen("stud.dat","r+t");

printf("Enter the Roll no. to modify :");

scanf("%d",&roll);

while (fread(&s1,sizeof(s1),1,ptr))

{ if (s1.rno==roll)

{

offset=ftell(ptr)-sizeof(s1);

fseek(ptr,offset,SEEK_SET);

s1.rno=roll;

printf("Name :");

scanf("%s",s1.name);

printf("Age :");

scanf("%d",&s1.age);

printf("Marks :");

scanf("%d",&s1.marks);

fwrite(&s1,sizeof(s1),1,ptr);

found=1;

break;

}

}

if (found==0)

printf("\n\n.............Record Not Found..........\n");

fclose(ptr);

}

95

Page 96: CP II Manual Final

void search()

{

struct student s1;

int found=0,roll;

ptr=fopen("stud.dat","r");

printf("Enter the Roll no. to search :");

scanf("%d",&roll);

while (fread(&s1,sizeof(s1),1,ptr))

{

if (s1.rno==roll)

{

printf("\n\nRecord Found............");

printf("\nRoll No. :%d ",s1.rno);

printf("\nName :%s ",s1.name);

printf("\nAge :%d ",s1.age);

printf("\nMarks :%d ",s1.marks);

found=1;

break;

}

}

if (found==0)

printf("\n\n.............Record Not Found..........\n");

fclose(ptr);

}

OUTPUT:

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1-6): 5

Roll No.: 1

Name. : Arun

Age : 20

96

Page 97: CP II Manual Final

Marks : 90

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

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1-6): 3

Enter the Roll no. to modify :1

Name :Kumar

Age :25

Marks :97

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. Exit

Enter your option (1-6): 4

Enter the Roll no. to search :1

Record Found............

Roll No. :1

Name :Kumar

Age :25

Marks :97

1. Add

2. Delete

3. Modify

4. Search

5. Display

6. ExitEnter your option (1-6):6

***************************************************************

97

Page 98: CP II Manual Final

13. Extend the above program to move the file pointer to the beginning of the file

using fseek().

#include <stdio.h>

#include <stdlib.h>

int main()

{

long int x;

int i=0;

char c,str[25];

FILE *ptr;

system("clear");

ptr=fopen("st.txt","w+");

printf("Enter a string : \n");

while ((c=getchar()) != '\n')

putc(c,ptr);

fseek(ptr,0L,SEEK_SET);

x=ftell(ptr);

printf("\nPtr is at the begining of the file, Ptr= %ld\n",x);

printf("\n\nThe String stored in the file is : " );

while ((c=getc(ptr)) != EOF)

putchar(c);

fclose(ptr);

return 1

}

OUTPUT:

[staff@localhost ~]$ cc p315.c

[staff@localhost ~]$ ./a.out

Enter a string :

Hello

Ptr is at the begining of the file, Ptr= 0

The String stored in the file is : Hello

[staff@localhost ~]$

***************************************************************

98

Page 99: CP II Manual Final

14. Write a C program to define a macro for finding the largest of three numbers.

#include <stdio.h>

#define max(a,b,c) (((a>b)&&(a>c))?a:(b>c)?b:c)

int main()

{

int a,b,c;

printf("enter three numbers: ");

scanf("%d%d%d",&a,&b,&c);

printf("Largest : %d\n",max(a,b,c));

}

OUTPUT:

[staff@localhost ~]$ cc large.c

[staff@localhost ~]$ ./a.out

enter three numbers: 5 7 2

Largest : 7

[staff@localhost ~]$

***************************************************************

15. Write a C program to define a macro for displaying the given string.

#include <stdio.h>

#define print(msg) printf(msg)

int main()

{

print("Hello\n");

}

OUTPUT:

[staff@localhost ~]$ ./a.out

Hello

[staff@localhost ~]$

***************************************************************

99

Page 100: CP II Manual Final

SUPPLEMENTARY PROGRAMS:

SHELL PROGRAMMING

100

Page 101: CP II Manual Final

1. Write a shell script to find the minimum of three numbers.

[staff@localhost ~]$ cat pa21

echo "Enter valuefor A, B and C"

read a

read b

read c

if test $a -lt $b -a $a -lt $c

then

echo "$a is smallest number"

elif test $b -lt $c

then

echo "$b is smallest number"

else

echo "$c is smallest number"

fi

OUTPUT

[staff@localhost ~]$ sh pa21

Enter valuefor A, B and C

45

2

12

2 is smallest number

***************************************************************

2. Write a shell script to read a number and find its square and cube.

[staff@localhost ~]$ cat pa22

# to find square and cube of a number

echo " enter a number"

read n

sn=`expr $n \* $n`

cn=`expr $sn \* $n`

echo " Square of n=$n is $sn"

echo " cube of n=$n is $cn"

OUTPUT

[staff@localhost ~]$ sh pa22

enter a number

4

101

Page 102: CP II Manual Final

Square of n=4 is 16

cube of n=4 is 64

***************************************************************

3. Write a shell script to find area of a circle.

# area of a circle

echo "Enter r Value"

read r

echo $r

c=`expr "scale=2; ( 3.14 * $r * $r ) " | bc `

#c=`expr $c \* 5 / 9`

echo "Area of a circle = $c"

OUTPUT

[staff@localhost ~]$ sh pa23

Enter r Value

5

5

Area of a circle = 78.50

***************************************************************

4. Write a shell script to find the simple interest.

[staff@localhost ~]$ cat pa24

# Simple interest

echo "Enter Principal Value"

read p

echo "Enter year value"

read n

echo " Enter rate of interest"

read r

c=`expr "scale=2; ( $p * $n * $r ) / 100 " | bc `

#c=`expr $c \* 5 / 9`

echo "Simple Interest = $c"

OUTPUT

[staff@localhost ~]$ sh pa24

Enter Principal Value

10000

Enter year value

102

Page 103: CP II Manual Final

2

Enter rate of interest

10

Simple Interest = 2000.00

***************************************************************

5. Write a shell script to check whether the given number is divisible by 4 and

7.

[staff@localhost ~]$ cat pa25

# Check whether number is divisible by 4 and 7

echo "Enter a number..."

read n

d1=`expr $n % 4`

d2=`expr $n % 7`

if [ $d1 -eq 0 -a $d2 -eq 0 ]

then

echo " number=$n is divisible by 4 and 7"

else

echo " number=$n is not divisible by 4 and 7"

fi

OUTPUT

[staff@localhost ~]$ sh pa25

Enter a number...

28

number=28 is divisible by 4 and 7

[staff@localhost ~]$ sh pa25

Enter a number...

20

number=20 is not divisible by 4 and 7

***************************************************************

6. Write a shell script to check whether the given year is leap year or not.

PROGRAM

[staff@localhost ~]$ cat pa26

# leap year or not

echo "Enter a year..."

read n

103

Page 104: CP II Manual Final

d1=`expr $n % 4`

if [ $d1 -eq 0 ]

then

echo " $n year is leap year"

else

echo " $n year is not a leap year"

fi

OUTPUT

sh pa26

Enter a year...

2012

2012 year is leap year

***************************************************************

7. Write a Shell script to read a filename from the user and to display the file

permission of the file.

[staff@localhost ~]$ cat pa27

# to read a filename from the user and to display the owner of the file

echo "Enter a file name "

read name

ls -l > tmp

if(grep $name tmp > tmp1)

then

# tr -s , --squeeze-repeats replace each input sequence of a repeated character

# with a single occurrence of that character

# cut -Prints selected parts of lines from each FILE to standard output.

# cut -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter

# cut -f, --fields=LIST select only these fields; f1 - first field

line=`cat tmp1|tr -s " "|cut -d" " -f1`

fi

check=`echo $line |wc -c`

echo " line = $line"

echo "check= $check"

if test $check -gt 1

then

echo " the permissions of the file $name is $line"

104

Page 105: CP II Manual Final

else

echo "The file $name does not exist"

fi

OUTPUT

[staff@localhost ~]$ sh pa27

Enter a file name

file1.txt

line = -rw-rw-r--

check= 11

the permissions of the file file1.txt is -rw-rw-r—

***************************************************************

8. Write a Shell script to read a file name from the user and assign read, write

and execute permissions for that particular file.

# to assign all rights to a file

echo " Enter a file name:"

read fname

ls -l $fname

chmod 777 $fname

echo "permissions are given"

ls -l $fname

OUTPUT

Enter a file name:

file1.txt

-rw-rw-r-- 1 staff staff 92 Jan 23 16:11 file1.txt

permissions are given

-rwxrwxrwx 1 staff staff 92 Jan 23 16:11 file1.txt

9. Write a Shell script to prepare a grocery bill for 4 items.

[staff@localhost ~]$ cat pa28

# Grocery Bill Details

echo " Enter the Item1 Quantity and Price "

read q1

read p1

echo " Enter the Item2 Quantity and Price "

read q2

read p2

105

Page 106: CP II Manual Final

echo " Enter the Item3 Quantity and Price "

read q3

read p3

echo " Enter the Item4 Quantity and Price "

read q4

read p4

bill=`expr "scale=2; ($q1 * $p1) + ($q2 * $p2) + ($q3 * $p3) +( $q4 * $p4)" | bc`

echo "Grcery Bill = $bill"

OUTPUT

[staff@localhost ~]$ sh pa28

Enter the Item1 Quantity and Price

2

5.50

Enter the Item2 Quantity and Price

3

6

Enter the Item3 Quantity and Price

4

7

Enter the Item4 Quantity and Price

5

8

Grcery Bill = 97.00

***************************************************************

10. Write a Shell script to generate Fibonacci series.

[staff@localhost ~]$ cat pa29

# Fibonacci Numbers

echo "Enter the Value for n"

read n

i1=0

i2=1

i3=`expr $i1 + $i2`

echo "$i1 $i2 $i3"

i=3

while [ $i -lt $n ]

106

Page 107: CP II Manual Final

do

i1=$i2

i2=$i3

i3=`expr $i1 + $i2`

i=`expr $i + 1`

echo "$i3"

done

OUTPUT

[staff@localhost ~]$ sh pa29

Enter the Value for n

10

0 1 1

2

3

5

8

13

21

34

***************************************************************

11. Write a Shell script to reverse the given number.

[staff@localhost ~]$ cat pa211

# reverse of a Number

echo " Enter the number: "

read n

temp=$n

r=0

while [ $n -gt 0 ]

do

a=`expr $n % 10`

r=`expr $r \* 10 + $a`

n=`expr $n / 10`

done

echo "Number typed is $temp and the reverse is $r"

107

Page 108: CP II Manual Final

OUTPUT

[staff@localhost ~]$ sh pa211

Enter the number:

54321

Number typed is 54321 and the reverse is 12345

***************************************************************

12. Write a Shell script to check whether the given number is Armstrong

number or not.

[staff@localhost ~]$ cat pa212

# Armstrong Number

echo " Enter the number: "

read n

temp=$n

r=0

while [ $n -gt 0 ]

do

a=`expr $n % 10`

r=`expr $a \* $a \* $a + $r`

n=`expr $n / 10`

done

if [ $r -eq $temp ]

then

echo "Number typed $temp is an armstrong number "

else

echo " number typed $temp is not an armstrong number "

fi

OUTPUT

[staff@localhost ~]$ sh pa212

Enter the number:

153

Number typed 153 is an armstrong number

[staff@localhost ~]$ sh pa212

Enter the number:

1234

number typed 1234 is not an armstrong number

***************************************************************

108

Page 109: CP II Manual Final

13. Write a Shell script to read n numbers and find their sum.

[staff@localhost ~]$ cat pa213

# Sum of N numbers

echo " How many numbers you want to add ?... "

read n

i=1

s=0

while [ $i -le $n ]

do

echo " Enter $i number"

read a

s=`expr $s + $a `

i=`expr $i + 1`

done

echo "The Sum of $n numbers = $s"

OUTPUT

[staff@localhost ~]$ sh pa213

How many numbers you want to add ?...

7

Enter 1 number

1

Enter 2 number

2

Enter 3 number

3

Enter 4 number

4

Enter 5 number

5

Enter 6 number

6

Enter 7 number

7

The Sum of 7 numbers = 28

***************************************************************

109

Page 110: CP II Manual Final

14. Write a Shell script to compare two strings. ( hint use = operator ).

[staff@localhost ~]$ cat pa214

# String Compare

echo " Enter the first string :.. "

read s1

echo "Enter second string :.."

read s2

if [ $s1 = $s2 ]

then

echo "$s1 and $s2 are equal"

else

echo "$s1 and $s2 are not equal "

fi

OUTPUT

[staff@localhost ~]$ sh pa214

Enter the first string :..

ksr

Enter second string :..

ksriet

ksr and ksriet are not equal

**************************************************************

15. Write a Shell script to find the length of the given string.

[staff@localhost ~]$ cat pa215

# length of string

echo " Enter the string : "

read s1

l=`expr $s1 | wc -c `

l=`expr $l - 1`

echo " The length of the given string $s1 is $l"

OUTPUT

[staff@localhost ~]$ sh pa215

Enter the string :

computer

The length of the given string computer is 8

***************************************************************

110

Page 111: CP II Manual Final

16. Write a Shell script to develop a menu driven program to execute any 5

UNIX commands.

[staff@localhost ~]$ cat pa216

# Menu driven program for 5 unix commands

while true

do

echo " Menu "

echo " 1. Today's date"

echo " 2. List of users "

echo " 3. Current working directory "

echo " 4. Process State "

echo " 5. Free disk Space "

echo " 6. Quit"

read ch

case $ch in

1) date;;

2) who;;

3) pwd;;

4) ps;;

5) df;;

6) break;;

*) echo "Invalid choice "

esac

done

OUTPUT

[staff@localhost ~]$ sh pa216

Menu

1. Today's date

2. List of users

3. Current working directory

4. Process State

5. Free disk Space

6. Quit

1

Tue Jan 24 16:12:55 IST 2012

Menu

1. Today's date111

Page 112: CP II Manual Final

2. List of users

3. Current working directory

4. Process State

5. Free disk Space

6. Quit

2

root tty1 2012-01-24 09:10

staff pts/0 2012-01-24 14:44 (192.168.5.11)

staff2 pts/1 2012-01-24 14:46 (192.168.5.14)

staff pts/2 2012-01-24 10:36 (192.168.5.12)

Menu

1. Today's date

2. List of users

3. Current working directory

4. Process State

5. Free disk Space

6. Quit

3

/home/staff

Menu

1. Today's date

2. List of users

3. Current working directory

4. Process State

5. Free disk Space

6. Quit

4

PID TTY TIME CMD

12944 pts/2 00:00:00 bash

13779 pts/2 00:00:00 ksh

13780 pts/2 00:00:00 csh

21477 pts/2 00:00:00 sh

21676 pts/2 00:00:00 ps

Menu

1. Today's date

2. List of users

3. Current working directory

4. Process State

112

Page 113: CP II Manual Final

5. Free disk Space

6. Quit

6

***************************************************************

17. Write a Shell script to find the number of ordinary files and directories in the

current directory. ( hint: use ls –l | grep –c “^d” command for directory

count

[staff@localhost ~]$ cat pa217

# File and Directory Count in the current working directory

var1=`ls -l | grep -c "^d"`

var2=`ls -l | grep -c "^-"`

echo " File count = $var2"

echo " Directory count= $var1"

OUTPUT

[staff@localhost ~]$ sh pa217

File count = 87

Directory count= 1

***************************************************************

18. Write a shell script to count the number of digits in a given number

# Number of digits in a Number

echo " Enter the number: "

read n

temp=$n

sd=0

while [ $n -gt 0 ]

do

a=`expr $n % 10`

sd=`expr $sd + 1`

n=`expr $n / 10`

done

echo "Number typed is $temp and the number of digits in the given number is $sd"

OUTPUT[staff@localhost ~]$ sh pa218

Enter the number:

54544

Number typed is 54544 and the number of digits in the given number is 5

***************************************************************

113