0% found this document useful (0 votes)
2K views

1) Write A Shell Script That Accepts Command Line Arguments and Prints Them in Reverse Order

The document provides examples of shell script programs that perform various tasks like: 1. Accepting command line arguments and printing them in reverse order. 2. Comparing file permissions of two files given as arguments and printing the permissions. 3. Checking if a given string is a palindrome. 4. Sorting and merging two files given as arguments. 5. Printing the digits of a number in reverse order. 6. Locking and unlocking the terminal by prompting for a password. 7. Checking if a given login name exists and printing the home directory. 8. Determining the number of links of a given file. 9. Displaying the

Uploaded by

ram
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

1) Write A Shell Script That Accepts Command Line Arguments and Prints Them in Reverse Order

The document provides examples of shell script programs that perform various tasks like: 1. Accepting command line arguments and printing them in reverse order. 2. Comparing file permissions of two files given as arguments and printing the permissions. 3. Checking if a given string is a palindrome. 4. Sorting and merging two files given as arguments. 5. Printing the digits of a number in reverse order. 6. Locking and unlocking the terminal by prompting for a password. 7. Checking if a given login name exists and printing the home directory. 8. Determining the number of links of a given file. 9. Displaying the

Uploaded by

ram
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Downloaded from www.pencilji.

com

1) Write a shell script that accepts command line arguments and prints them in reverse order.
echo "Checking the number of arguments" if [ $# -eq 0 ] then echo "No arguments supplied" exit fi n=$# while [ $n -gt 0 ] do eval echo \$$n n=`expr $n - 1` done

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ Checking the number of No arguments supplied [root@localhost unix]$ Checking the number of great are indians [root@localhost unix]$ sh prg01.sh arguments sh prg01.sh indians are great arguments

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

2) Write a shell script, which takes two filenames as command line arguments and checks, whether two files have identical file permissions and print. If not, print filenames and their permissions separately.
if [ $# -eq 0 ] then echo "No filename given" exit elif [ $# -eq 1 ] then echo "Only one filename is given" exit else echo "Two filenames given" fi if [ ! -e $1 -a ! -e $2 ] then echo "Both files does not exist" exit fi if [ ! then echo exit fi if [ ! then echo exit fi -e $1 ] "File 1 does not exist" -e $2 ] "File 2 does not exist"

x=`ls -l $1 | cut -c 2-10` y=`ls -l $2 | cut -c 2-10` if [ $x = $y ] then echo "Common permissions" else echo "Uncommon permissions" echo "File 1:" $x echo "File 2:" $y fi

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [mca3a6@localhost mca3a6]$sh prg2.sh Insufficient number of arguments [root@localhost unix]$sh prg2.sh a1 only one file name is given,Insufficient[root@localhost unix]$ [root@localhost unix]$sh prg2.sh f1 f2 Two file names are given Two files exists Two file permissions are same File permission: rw-rw-r-[root@localhost unix]$chmod u+x f2 [root@localhost unix]$sh prg2.sh f1 f2 Two file names are given Two files exists Different file permissions File1: rw-rw-r-File2: rwxrw-r-[root@localhost unix]$ _

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

3) Write a shell script to check whether the given string is palindrome or not.
echo "Enter a string:- " read str len=`echo $str | wc -c` len=`expr $len - 1` i=1 while [ $len -ge $i ] do ch=`echo $str | cut -c $i` ch1=`echo $str | cut -c $len` if [ $ch != $ch1 ] then echo "The given string is not a palindrome" exit fi len=`expr $len - 1` i=`expr $i + 1` done OUTPUT: [mca3a6@localhost mca3a6]$ sh prg03.sh Enter any string madam The entered string is palindrome [mca3a6@localhost mca3a6]$ sh prg03.sh Enter any string sir The string is not a palindrome [mca3a6@localhost mca3a6]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

4) Write a shell script to do the following actions:a) Accept two filenames as an argument. b) Sort both the files to temporary file and merge the sorted file to get the final output. Finally remove the temporary file.
if [ $# -ne 2 ] then echo "Invalid arguments" exit fi sort $1>tempfile1 sort $2>tempfile2 echo "Sorted Merged file is" sort -m tempfile1 tempfile2 | sort -n rm tempfile1 tempfile2 OUTPUT: [root@localhost unix]$ sh file.sh Invalid arguements

[root@localhost unix]$ sh file.sh mat Invalid arguements 1 2 2 [[root@localhost unix]$ sh file.sh mat mat1 1 123 2 2 456 789 [root@localhost unix]$ sh file.sh f1 f2 hi how [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

5) Write a shell script to accept a number and print the digits of that number in reverse order.
echo "Enter a number: " read num rev=0 if [ $num -lt 0 ] then echo "Positive number has to be entered" exit fi while [ $num -gt 0 ] do rem=`expr $num % 10` rev=`expr $rev \* 10 + $rem` num=`expr $num \/ 10` done echo "The reverse of the given number is:" echo $rev

OUTPUT: [root@localhost unix]$ sh prg04.sh Enter a positive number 6 usage!Input atleast two digit number [root@localhost unix]$ sh prg04.sh Enter a positive number 56 Reverse of the given number 56 is: 65 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

6) Write a shell script to lock the terminal.


clear echo "Enter your password" stty -echo read p1 stty echo echo "Confirm your password: " stty -echo read p2 stty echo if [ "$p1" != "$p2" ] then echo "Confirmation mistake" exit fi clear echo "Screen locked" echo "To open the lock re-enter the password" stty -echo read p3 stty echo while [ "$p3" != "$p1" ] do echo "Wrong password" echo "Enter the password again" stty -echo read p3 stty echo done clear echo "Screen is unlocked" exit

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ sh terloc.sh enter password confirm password confirmation mistake [root@localhost unix]$ sh terloc.sh enter password confirm password screen locked to open the lock , re-enter the password wrong password try again re-enter the password screen unlocked [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

7) Write a shell script which accepts command line arguments and checks whether it is a valid login name or not. If it is valid, print the login name and home directory.
if [ $# -eq 0 ] then echo "No arguments" exit else for x in $* do if grep "^$x:" /etc/passwd>temp then y=`cut -d ":" -f 6 temp` echo "Login name= " $x echo "Home directory= " $y else echo "Login name does not exist" fi done fi

OUTPUT: [root@localhost unix]$ sh prg05.sh No arguments [root@localhost unix]$ sh prg05.sh mca3a10 LOGIN NAME:= mca3a10 DIR NAME:= /home/mca3a10 [root@localhost unix]$ sh prg05.sh mca Login doesnt exist [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

8) Write a shell script to determine the number of links of the given file name as command line arguments.
if [ $# -eq 0 ] then echo "Insufficient data" echo "Usage: Script name, filename, directory" exit elif [ $# -eq 2 ] then dir=$2 else dir=`pwd` fi cd $dir if [ ! -e $1 ] then echo "File $1 does not exist" exit fi file=$1 set -- `ls -l $file` link=$2 if [ $link -eq 1 ] then echo "File has no links" else echo "File has $link links" fi set -- `ls -i $file` inode=$1 find $dir -inum $inode -print

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ sh links.sh 123 123 does not exist [root@localhost unix]$ sh links.sh p.sh ls: file: No such file or directory links.sh: [: -eq: unary operator expected File has links /home/mca3a6/p.sh /home/mca3a6/q.sh /home/mca3a6/r.sh [root@localhost unix]$ sh links.sh prg02.sh prg02.sh does not exist [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

9) Write a shell script to display current month calendar in which todays date is replaced by * or **.
#!bin/bash a=`date +%e` if [ $a -lt 10 ] then cal|sed "s/$a/*/" else cal|sed "s/$a/**/" fi

OUTPUT:

[root@localhost unix]$ sh prg10.sh November 2007 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 ** 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

10) Write an AWK shell script that folds long line into new colomns. Thus any line that exceeds 5 characters must be broken into after 5 th Character and / be appended as an indication of folding and processing is to be continued with residue.
awk ' { str=$0 while(length(str)>5) { printf("%s\\\n",substr(str,1,5)) str=substr(str,6,length(str)-5); } print str } ' $@

OUTPUT: [root@localhost unix]$ sh prg11.sh all the students in our college read well told the teacher all t\ he st\ udent\ s in \ our c\ olleg\ e rea\ d wel\ l tol\ d the\ teac\ her [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

11) Write an AWK program to find the transpose of a given matrix.


BEGIN{ j=0 printf("Entered matrix is\n") } { for(i=1;i<=NF;i++) { a[j++]=$i; printf("%s\t",$i); } printf("\n"); } END{

printf("Transpose of matrix is"); for(i=0;i<NF;i++) { k=i; printf("\n"); for(j=0;j<NR;j++) { if(a[k]>=0&&a[k]<=9) printf("%s\t",a[k]); else printf("%s\t",a[k]); k=k+NF; } } printf("\n"); }

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ awk -f prg8.awk mat1 Entered matrix is 1 2 3 4 5 6 7 8 9 Transpose of matrix is 1 4 7 2 5 8 3 6 9 [root@localhost unix]$ cat>mat2 10 20 30 40 50 60 70 80 90 [root@localhost unix]$ cat mat2 10 20 30 40 50 60 70 80 90 [root@localhost unix]$ awk -f prg8.awk mat2 Entered matrix is 10 20 30 40 50 60 70 80 90 Transpose of matrix is 10 40 70 20 50 80 30 60 90 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

12) Write a shell program which accepts command line argument and creates directoris in hierarchical order.
if [ $# -eq 0 ] then echo "Insufficient Arguments" exit fi IFS=`/` for dirname in $* do mkdir $dirname cd $dirname done

OUTPUT:

[root@localhost unix]$ sh prg9.sh Insufficient Arguments [root@localhost unix]$ sh prg9.sh bangalore/rnsit/mca [root@localhost unix]$ cd bangalore [root@localhost bangalore]$ ls rnsit [root@localhost bangalore]$ cd rnsit [root@localhost rnsit]$ ls mca [root@localhost rnsit]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

1. Write a LEX program to count number of blank spaces, characters, lines, words from a given text.
%{ int bcount=0,ccount=0,lcount=0,wcount=0; %} %% [^ \t\n]+ {wcount++;ccount+=yyleng;} \n { lcount++; } " " { bcount++;ccount;} . {ccount++; } %% main() { printf("Enter the text"); yylex(); printf("word=%d\n char=%d\n line=%d\n blankspace=%d\n",wcount,ccount,lcount,bco nt); } OUTPUT: [root@localhost unix]$ lex lex1.l [root@localhost unix]$ cc lex.yy.c -ll [[root@localhost unix]$./a.out Enter the text this is linux red hat enterpise as version word=8 char=35 line=2 blankspace=8 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

2. Write a LEX program to count number of positive and negative integers and fractions.
%{ int pint=0,nint=0,pfr=0,nfr=0; %} %% \+?[0-9]+ {pint++;} -[0-9]+ {nint++;} \+?[0-9]*\.[0-9]+ {pfr++;} -[0-9]*\.[0-9]+ {nfr++;} . {} %% main() { printf("Enter the no.: "); yylex(); printf("pos int=%d\n neg int=%d",pint,nint); printf("pos frac=%d\n neg frac=%d",pfr,nfr); } OUTPUT:

[root@localhost unix]$ lex lex2.l [root@localhost unix]$ cc lex.yy.c -ll [root@localhost unix]$./a.out
Enter the no.: 5 7 8 -43 -45 -44.6 -7.3 7.8 4.8 pos int=3 neg int=2pos frac=2 neg frac=2 [mca3a5@localhost mca3a5]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

3. Write a LEX program to check whether the given arithmetical expression is valid or not and print number of operators and operands.
%{ int flag=1; int oprc=0,digic=0,top=-1; char stack[10]; %} digit [0-9]+ opr[+*/-] %% ['('] {stack[++top]='(';} [')'] {flag=1; if((stack[top]!='(') && (top!=-1)) { printf("INVALID EXPRN\n"); exit(0); } top--; } {digit} {digic++; } {opr}/{digit} {oprc++; } {opr}/['('] {oprc++; } . { printf("INVALID");exit(0);} %% main() { yylex(); if(((oprc+1 == digic)||(oprc == digic)) && (top == -1)) { printf("VALID EXPRN\n"); printf("NUMBER OF OPERATORS : %d\nNUMBER OF OPERANDS : %d",oprc digic); } else { printf("INVALID EXPN"); } }

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

OUTPUT: [root@localhost unix]$ lex lexexprn.l [root@localhost unix]$ cc lex.yy.c -ll [root@localhost unix]$./a.out
(3+1) VALID EXPRN NUMBER OF OPERATORS : 1 NUMBER OF OPERANDS : 2[mca3a8@localhost mca3a8]$ ./a.out 3*% INVALID

[root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

4. Write a LEX program to check whether a given sentence is simple or compound.


%{ int flag=0; %} %% and flag=1; or flag=1; but flag=1; %% main() { yylex(); if(flag) { printf("ITS A COMPUND STATEMENT\n"); } else { printf("ITS A SIMPLE STATEMENT"); } }

OUTPUT: [root@localhost unix]$ lex lexsimp.l [root@localhost unix]$ cc lex.yy.c -ll [root@localhost unix]$ ./a.out
me and my friend went to the market me my friend went to the market ITS A COMPUND STATEMENT [root@localhost unix]$ ./a.out I am a writer I am a writer ITS A SIMPLE STATEMENT

[root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

5. Write a LEX program to count number of printf and scanf from a given c program file and replace them with write and read respectively.

%{ int pcount=0,scount=0; %} %% printf {pcount++,fprintf(yyout,"write ");} scanf {scount++,fprintf(yyout,"read ");} %% main() { yyin = fopen("dee.c","r"); yyout = fopen("dee2.c","w"); yylex(); printf("NUMBER OF PRINTF = %d\n NUMBER OF SCANF = %d",pcount,scount); }

OUTPUT: [root@localhost unix]$ lex lexcountpfsf.l [root@localhost unix]$ cc lex.yy.c -ll [root@localhost unix]$./a.out
NUMBER OF PRINTF = 2 NUMBER OF SCANF = 1 [mca3a8@localhost mca3a8]$ cat dee2.c #include(stdio.h) main() { int a,b; write ("ENTER 2 NUM\n"); read ("%d %d",&a,&b); write ("SUM = %d",a+b); }

[root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

6. Write a LEX program to count number of vowels and consonants.


%{ int vow=0; int con=0; %} %% [aeiouAEIOU] {vow++;} [a-zA-Z] {con++;} %% main() { printf("enter the string\n"); yylex(); printf("\n the number of vowels in a string is %d \n",vow); printf("\n the number of consonents in a string is %d \n",con); } OUTPUT: [root@localhost unix]$ lex vowcons.l [root@localhost unix]$ cc lex.yy.c -ll [root@localhost unix]$ ./a.out enter the string hello friends do unix programs its interesting. . the number of vowels in a string is 14 the number of consonents in a string is 26 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

1. Write a YACC program to recognize the grammer [ an b/n>0] . Test whether the following string belongs to this grammer.
%{ #include<stdio.h> %} %token a b %% st:st reca endb '\n' {printf("STRING BELONGS TO GRAMMER");} | |error '\n'{yyerror("DOES NOT BELONG TO GRAMMER");yyerrok;} reca:enda reca | ; enda:a; endb:b; %% main() { printf("Enter the text :"); yyparse(); } yylex() { char c; while((c=getchar())==' '); if(c=='a')return a; if(c=='b')return b; return c; } yyerror(char *s) { printf("%s",s); }

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ yacc -d yacc1.y [root@localhost unix]$cc y.tab.c -ll [root@localhost unix]$ ./a.out Enter the text :a syntax errorDOES NOT BELONG TO GRAMMERb STRING BELONGS TO GRAMMERaaaaab STRING BELONGS TO GRAMMERba syntax errorDOES NOT BELONG TO GRAMMER [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

2. write a YACC program to recognize the grammer [a n bn /n>0].


%{ #include<stdio.h> %} %token a b %% st:st reca endb '\n'{printf("STRING BELONG TO GRAMMAR ");} |st'\n'{printf("WHR N VALUE IS 0");} | |error '\n'{yyerror("DOES NOT BELONG TO THE GRAMMAR");yyerrok;} ; reca:enda reca endb|enda enda:a; endb:b; %% main() { printf("Enter the text :"); yyparse(); } yylex() { char c; while((c=getchar())==' '); if(c=='a') return a; if(c=='b') return b; return c; } yyerror(char *s) { printf("%s",s); }

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost unix]$ yacc yacc2.y [root@localhost unix]$ cc y.tab.c -ll [root@localhost unix]$ ./a.out Enter the text :aab syntax errorDOES NOT BELONG TO THE GRAMMARaabb STRING BELONG TO GRAMMAR abv syntax errorDOES NOT BELONG TO THE GRAMMARab STRING BELONG TO GRAMMAR baa syntax errorDOES NOT BELONG TO THE GRAMMAR WHR N VALUE IS 0 [root@localhost unix]$

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com

3. write a YACC program to evaluate an arithmetic expression.


%{ #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<string.h> #define YYSTYPE double %} %token num %left '+' '-' %left '*' '/' %% st: st expr '\n' {printf("value is = %f \n",$2);} |st '\n' | |error '\n' {printf("invalid\n");} ; expr: num {$$=$1;} |expr '+' expr {$$=$1+$3;} |expr '-' expr {$$=$1-$3;} |expr '*' expr {$$=$1*$3;} |expr '/' expr { if($3==0) { printf("division by zero!\n"); exit(0); } else $$=$1/$3; } |'(' expr ')' ; %% main() { printf("enter an expression to evaluate:"); yyparse(); } yylex() { int ch; while((ch=getchar())==' '); if(isdigit(ch)|ch=='.') { ungetc(ch,stdin); scanf("%lf",&yylval);

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com return num; } return ch; } yyerror(char *s) { printf("%s",s); }

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com OUTPUT: [root@localhost yacc]$ yacc expr.y [root@localhost yacc]$ cc y.tab.c -ll [root@localhost yacc]$ ./a.out enter an expression to evaluate:4+5*7 value is = 39.000000 [root@localhost yacc]$ ./a.out enter an expression to evaluate:6/4 value is = 1.500000 [root@localhost yacc]$ ./a.out enter an expression to evaluate:9/0 division by zero! [root@localhost yacc]$

4. write a YACC program which recognizes a valid variable which starts with letter followed by a digit.
%{ #include<stdio.h> #include<ctype.h> %} %token let dig %% sat:let recld '\n'{printf("ACCEPTED\n");exit(0);} |let '\n' {printf("ACCEPTED\n");exit(0);} | |error '\n' {printf("INVALID");yyerrok;exit(0);} Downloaded from www.pencilji.com

Downloaded from www.pencilji.com ; recld:let recld |dig recld |let |dig ; %%

yylex() { char ch; while((ch=getchar())==' '); if(isalpha(ch)) return let; if(isdigit(ch)) return dig; return ch; } yyerror(char *s) { printf("%s",s); } main() { printf("ENTER THE STRING\n"); yyparse(); } OUTPUT: [root@localhost yacc]$ yacc yacc4.y [root@localhost yacc]$ cc y.tab.c -ll [root@localhost yacc]$ ./a.out ENTER THE STRING a4 ACCEPTED [root@localhost yacc]$ ./a.out ENTER THE STRING 7er syntax errorINVALID[root@localhost yacc]$ ./a.out ENTER THE STRING

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com $l syntax errorINVALID[root@localhost yacc]$ ./a.out ENTER THE STRING sum ACCEPTED [root@localhost yacc]$

5. write a YACC & LEX program to identify valid if and if-else statement. LEX PROGRAM :%{ #include<stdlib.h> #include<stdio.h> #include"y.tab.h" %} %% if return IF; else return ELSE; [a-zA-Z0-9+\-\*/=]+ return STAT; [a-zA-Z0-9+\-\*/=<>&!]+ return CONDITION; . return yytext[0]; %%

YACC PROGRAM:%{ int v=1; %} %token IF STAT CONDITION ELSE %nonassoc IF %nonassoc ELSE %% ifstruct: IF expr state1 |IF expr state1 ELSE state1 %prec ELSE ; state1: stmt |"{"state"}" |ifstruct %prec IF ; state: stmt|stmt state |ifstruct |ifstruct state ; expr: "("CONDITION")" |"("STAT")"

Downloaded from www.pencilji.com

Downloaded from www.pencilji.com ; stmt: STAT ";" |";" ; %% int yyerror(char *s) { v=0; } main() { yyparse(); if(v) printf("valid"); else printf("invalid"); }

OUTPUT:

[root@localhost yacc]$ lex lex55.l [root@localhost yacc]$ yacc lex55.y [root@localhost yacc]$ cc lex.yy.c y.tab.c -ll [root@localhost yacc]$ ./a.out ENTER THE IF-ELSE STATEMENT if(a>b) big=a; else big=b; valid[root@localhost yacc]$ ./a.out ENTER THE IF-ELSE STATEMENT if(a<0 invalid[root@localhost yacc]$

Downloaded from www.pencilji.com

You might also like