0% found this document useful (0 votes)
77 views36 pages

LSP Lab Solutions

The document provides examples of various Linux shell scripting concepts including: 1. Functions to break code into reusable sections. Examples demonstrate defining and calling functions. 2. Control flow structures like if/else, case statements, loops (for, while, until). Code snippets show conditional logic and looping. 3. Examples of common shell scripting tasks - finding max of 3 numbers, checking leap year, validating triangle angles, character classification, profit/loss calculation. 4. Comments explain the expr command and string operations in shell scripts. Overall the document serves as a reference for Linux shell script programming techniques.

Uploaded by

Uma Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views36 pages

LSP Lab Solutions

The document provides examples of various Linux shell scripting concepts including: 1. Functions to break code into reusable sections. Examples demonstrate defining and calling functions. 2. Control flow structures like if/else, case statements, loops (for, while, until). Code snippets show conditional logic and looping. 3. Examples of common shell scripting tasks - finding max of 3 numbers, checking leap year, validating triangle angles, character classification, profit/loss calculation. 4. Comments explain the expr command and string operations in shell scripts. Overall the document serves as a reference for Linux shell script programming techniques.

Uploaded by

Uma Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

To find Greatest among three numbers

Steps 
enter three numbers
if a > b and a>c then print a
else , if b > a and b > c then print b
else print c 
Program
 
# take a numbers from the user
echo "Enter a number: "
read a
read b
read c

# -gt is a greater sign here 


if [ $a -gt $b -a $a -gt $c ]
then
  echo "It's a."
elif [ $b -gt $a -a $b -gt $c ]
then
  echo "It's b."
else
  echo "It's c"
fi
 Output

To find a year is leap year or not


These are the conditions for a leap year :
The year is evenly divisible by 4;
If the year can be evenly divided by 100, it is NOT a leap year, unless;
The year is also evenly divisible by 400. Then it is a leap year.
Program
The expr command in Unix evaluates a given expression and displays its corresponding
output. It is used for:
Basic operations like addition, subtraction, multiplication, division, and modulus on integers.
Evaluating regular expressions, string operations like substring, length of strings etc.
echo "enter the year :"
read y
a=`expr $y % 4`
b=`expr $y % 100`
c=`expr $y % 400`
# -eq is for equal to
#-ne is for not equal to  
if [ $a -eq 0 -a $b -ne 0 -o $c -eq 0 ]
then
echo "$y is leap year"
else
echo "$y is not leap year"
fi
Output

Linux program to input angles of a triangle and find out whether it is valid triangle or not
Steps 
Input all three angles of triangle in some variable say angle1, angle2 and angle3.
Find sum of all three angles, store sum in some variable say sum = angle1 + angle2 + angle3.
Check if(sum == 180) then, triangle can be formed otherwise not. In addition, make sure
angles are greater than 0 i.e. check condition for angles if(angle1 != 0 && angle2 != 0 &&
angle3 != 0)
Program 
echo "enter  angle A"
read A
echo "enter angle B"
read B
echo "enter angle C"
read C
# sum all three angles
d=$((A+B+C))
if [ $A -eq 0 -o $B -eq 0 -o $C -eq 0 ]
then
echo "Enter angles greater than zero"
else
    if [ $d == 180 ];
    then
    echo "valid traingle"
    else
    echo "not a valid traingle"
    fi
fi
Output :  
Linux program to check whether a character is alphabet, digit or special character
Steps
A character is alphabet if it in between a-z or A-Z .
A character is digit if it is in between 0-9 .
A character is special symbol character if it neither alphabet nor digit.
Program
echo "enter a char"
read c
#set specified is [a-z], which is a shorthand way of
typing [abcdefghijklmnopqrstuvwxyz]
#set specified is [0-9], which is a shorthand way of typing [0123456789]
if [[ $c == [A-Z] ]];
then
    echo "you have entered an alphabet"
elif [[ $c == [a-z] ]];
then
    echo "you have entered an alphabet"
elif [[ $c == [0-9] ]];
then
    echo "you have entered is a digit"
else
    echo "you have entered a special symbols!"
fi
Output  

Linux Program to calculate profit or loss


Profit: When the selling price is more than the cost price, then the trader makes
a profit which is equal to SP - CP.
Loss: When the selling price is less than the cost price, then the trader makes a loss which is
equal to CP - SP.
Program
echo "input the cost price of an item"
read cp
echo "input the selling price of the item"
read sp
if [ $cp -eq $sp ]
then
echo "no profit or no gain"

fi
if [ $cp -gt $sp ]
then
s=$((cp - sp))
echo "loss of rs:$s"
else
s=$((sp - cp))
echo "profit of rs:$s"
fi
Output

While , Untill , For Loops Linux


Untill Loop 
The until loop continues running commands as long as the item in list continues to evaluate
true. Once an item evaluates false, the loop is exited. The syntax is:
until [ condition ]
do
   command1
   command2
   ...
   ....
   command n
done
Example 
c=0
until [ $c -gt 5 ]
do
  echo "C: $c"
  ((c++))
done
Output  
For Loop  
for (( EXP1; EXP2; EXP3 ))
do
command1
command2
command3
done 
Example
for (( c=1; c<=5; c++ ))
do 
   echo "Welcome "
done
Output 

Second method
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
Example
for i in 1 2 3 4 5
do
   echo "Welcome "
done
Output 

While Loop  
while command
do
   Statements
done 
Example 
a=0

while [ $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done
Output 
Write a shell script to print all even and odd number from 1 to 10
The expr command in Unix evaluates a given expression and displays its corresponding
output. It is used for: Basic operations like addition, subtraction, multiplication, division, and
modulus on integers. Evaluating regular expressions, string operations like substring, length of
strings etc.
Program 
echo "enter n value as range to calculate odd and even numbers."
read n
i=1
while [ $i -le $n ]
do
if [ `expr $i % 2` -eq 0 ]
then
echo even=$i
else
echo odd=$i
fi
i=`expr $i + 1`
done
Output
 
Write a shell script to print table of a given number
Program
echo "Enter a Number"
read n
i=1

while [ $i -le 10 ]
do
          echo " $n x $i = $(( n * i ))"
          i=$(( i + 1 ))
done
Output
Write a shell script to calculate factorial of a given number
Program
 
echo "Enter a number"
read n
f=1
while [ $n -gt 1 ]
do
  f=$((f * n))  #f = f * n
  n=$((n - 1))      #n= n - 1
done
echo $f
 Output

Write a shell script to print sum of all even numbers from 1 to 10


Program
echo "enter limit"
read n
i=2
while [ $i -lt $n ]
do
sum=$((sum+i))
i=$((i+2))
done
echo "sum:"$sum
Output 

Write a shell script to print sum of digit of any number


Program
echo -n "Enter number : "
read n
# store single digit
sd=0
# store number of digit
sum=0
# use while loop to caclulate the sum of all digits
while [ $n -gt 0 ]
do
    sd=$(( $n % 10 )) # get Remainder
    n=$(( $n / 10 ))  # get next digit
    sum=$(( $sum + $sd )) # calculate sum of digit
done
echo  "Sum of all digit  is $sum"
Output 

 
Use of case structure and use of break in shell scripting
Case structure
Shell supports case...esac statement which handles exactly this situation, and it does so more
efficiently than repeated if...elif statements.
The case statement allows you to easily check pattern (conditions) and then process a
command-line if that condition evaluates to true.
In other words the $variable-name is compared against the patterns until a match is found.
*) acts as default and it is executed if no match is found.
The pattern can include wildcards.
You must include ;; at the end of each command-n. The shell executes all the statements up
to the two semicolons that are next to each other.
The esac is always required to indicate end of case statement.
Syntax
case word in
   pattern1)
      Statement(s) to be executed if pattern1 matches
      ;;
   pattern2)
      Statement(s) to be executed if pattern2 matches
      ;;
   pattern3)
      Statement(s) to be executed if pattern3 matches
      ;;
   *)
     Default condition to be executed
     ;;
esac
Example
echo "Enter a number"
 read num
 case $num in
 [0-9])
 echo “you have entered a single digit number”
 ;;
 [1-9][1-9])
 echo “you have entered a two-digit number”
 ;;
 [1-9][1-9][1-9])
 echo “you have entered a three-digit number”
 ;;
 *)
 echo “your entry does not match any of the conditions”
 ;;
 esac
Output

break statement
break command is used to terminate the execution of for loop, while loop and until loop. It
can also take one parameter i.e.[N]. Here n is the number of nested loops to break. The default
number is 1.
Example
for i in `seq 1 10`
do
if(($i ==5))
then
break
fi
echo $i
done
Output

Write a shell script to make a basic calculator which performs addition, subtraction, division
and multiplication
Program
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read c
case $c in
  1)echo "sum $((a + b))"  ;;
  2)echo "subtraction $((a - b ))"  ;;
  3)echo "multiplication $((a * b))" ;;
  4)echo  "division $((a / b))"  ;;
  *) echo "enter valid operation"
esac
Output

Write a shell script to print days of a week


Shell supports case...esac statement which handles exactly this situation, and it does so more
efficiently than repeated if...elif statements.
The case statement allows you to easily check pattern (conditions) and then process a
command-line if that condition evaluates to true.
In other words the $variable-name is compared against the patterns until a match is found.
*) acts as default and it is executed if no match is found.
The pattern can include wildcards.
You must include ;; at the end of each command-n. The shell executes all the statements up
to the two semicolons that are next to each other.
The esac is always required to indicate end of case statement.
Program
echo "enter a number"
read n
case $n in
1) echo "Sunday" ;;
2) echo "Monday" ;;
3) echo "Tuesday" ;;
4) echo "Wednesday" ;;
5) echo "Thursday" ;;
6) echo "Friday" ;;
7) echo "Saturday" ;;
*) echo "enter value between 1 to 7" ;;
esac
Output

Write a shell script to print days of each months


Program
for m in {1..12};
do
  a=$(date -d "$m/1 + 1 month - 1 day" "+%b - %d days";)
  echo "$a"
done 
Output
Implementation of shell script using Functions
Functions
Functions enable you to break down the overall functionality into sections, which can then be
called upon to perform their individual tasks when needed. Using functions to perform repetitive
tasks is an excellent way to create code reuse.Shell functions are similar to subroutines,
procedures, and functions in other programming languages .
Syntax 
function_name ()

   list of commands
}
Example
function f
{
   echo "Hello World"
}
res=`f`
echo "$res"
 Output

Passing Parameters to a Function


You can define a function that will accept parameters while calling the function.
Example
echo "enter "
read y
function func
{
   echo "Hello World"
}
# Invoke your function
res=`func $y`
echo "$res"
Output
Passing Parameters to a Function
You can define a function that will accept parameters while calling the function.
Example
echo "enter "
read y
function func
{
   echo "Hello World"
}
# Invoke your function
res=`func $y`
echo "$res"
Output

Returning Values from Functions


you can return any value from your function using the return command
Example
function func () {
   echo "Hello $1 $2"
   return 1
}
#passing parameters
func  Aman amita

# Capture value returnd by last command


res=$?

echo "Return value is $res"


Output

Nested Functions
One of the more interesting features of functions is that they can call themselves and also
other functions. A function that calls itself is known as a recursive function.
Example
 f1 () {
   echo "first function "
   f2
}
f2 () {
   echo "second function"
}
res=`one`
echo "$res"
 Output

Write a shell script to find a number is Armstrong or not


Steps
Start
read number 
set sum=0 and temp=number
reminder=number%10
sum=sum+(reminder*reminder*reminder)
number=number/10
repeat steps 4 to 6 until number > 0
if sum = temp
display number is armstrong
else 
display number is not armstrong
stop
Program
echo "Enter the number"
read n
function ams
{
t=$n
s=0
b=0
c=10
while [ $n -gt $b ]
do
r=$((n % c))
i=$((r * r * r))
s=$((s + i))
n=$((n / c))
done
echo $s
if [ $s == $t ]
then
echo "Amstrong number"
else
echo "Not an Armstrong number"
fi
}
result=`ams $n`
echo "$result"
Output
Write a shell script to find a number is palindrome or not
A palindrome number is a number that is same after reverse. 
For example 121, 34543, 343, 131, 48984 are the palindrome numbers.
Steps 
Get the number from user
Hold the number in temporary variable
Reverse the number
Compare the temporary number with reversed number
If both numbers are same, print palindrome number
Else print not palindrome number
Program
echo "Enter the number"
read n
function pal
{
number=$n
reverse=0
while [ $n -gt 0 ]
do
a=`expr $n % 10 `
n=`expr $n / 10 `
reverse=`expr $reverse \* 10 + $a`
done
echo $reverse
if [ $number -eq $reverse ]
then
    echo "Number is palindrome"
else
    echo "Number is not palindrome"
fi
}
r=`pal $n`
echo "$r"
 Output

Write a shell script to print Fibonacci series


 Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1
and 1, or 0 and 1, depending on the selected beginning point of the sequence, and each
subsequent number is the sum of the previous two.
Start
Declare variables i, a,b , show
Initialize the variables, a=0, b=1, and show =0
Enter the number of terms of Fibonacci series to be printed
Print First two terms of series
Use loop for the following steps
-> show=a+b
-> a=b
-> b=show
-> increase value of i each time by 1
-> print the value of show
End
Program
 echo "How many number of terms to be generated ?"
  read n
function fib
{
  x=0
  y=1
  i=2
  echo "Fibonacci Series up to $n terms :"
  echo "$x"
  echo "$y"
  while [ $i -lt $n ]
  do
      i=`expr $i + 1 `
      z=`expr $x + $y `
      echo "$z"
      x=$y
      y=$z
  done
}
r=`fib $n`
echo "$r"
Output
shell script to check whether a number is prime or not
program

echo "enter number"


read num
function prime
{
for((i=2; i<=num/2; i++))
do
  if [ $((num%i)) -eq 0 ]
  then
    echo "$num is not a prime number."
    exit
  fi
done
echo "$num is a prime number."
}
r=`prime $number`
echo "$r"
 
Output
Write a shell script to convert binary to decimal
Steps
Input the binary number.
Multiply each digit of the binary number with the power of 2 and add each multiplication
result.
The power starts from 0 to n-1 where n is the total number of digits in the binary number.
Program
echo "Enter the num"
read n
val=0
power=1
while [ $n  -ne 0 ]
       do
        r=`expr $n % 2`
        val=`expr $r \* $power + $val`
        power=`expr $power \* 10`
        n=`expr $n \/ 2`
      done
echo "Binary equivalent=$val"
Output
Shell script to print Diamond pattern
Program
echo "enter value of  n "
read num
for (( i=1;i<=$num ;i++))
do
   for (( j=$num;j>=i;j-- ))
   do
   echo -n " "
   done
   for (( c=1;c<=i;c++ ))
   do
   echo -n " *"
   sum=`expr $sum + 1`
   done
echo ""
done
d_max=`expr $num - 1`
for (( i=$d_max;i>=1;i--))
do
   for (( j=i;j<=$d_max;j++ ))
   do
   if [ $j -eq $d_max ]
   then
   echo -n " "
   fi
   echo -n " "
   done
   for (( c=1;c<=i;c++ ))
   do
   echo -n " *"
   sum=`expr $sum + 1`
   done
echo ""
done
 
Output
Shell script to print triangle pattern
Program
echo "enter value of n"
read rows
#-n -> allows not to append to next line
for((i=1; i<=rows; i++))
do
  for((j=1; j<=i; j++))
  do
    echo -n "* "
  done
  echo
done
Output

Shell script to print Square pattern


Program
 echo "enter value of n"
read rows
for((i=1; i<=rows; i++))
do
  for((j=1; j<=rows; j++))
  do
    echo -n "* "
  done
  echo
done
Output

Shell script to print Rectangle pattern


Program
echo "enter value of n"
read rows
echo "enter value of m"
read column
for((i=1; i<=rows; i++))
do
  for((j=1; j<=column; j++))
  do
    echo -n "* "
  done
  echo
done
Output
Shell script to print hollow square
Program
echo "enter the sizeof the square"
read size
clear
for (( i = 1; i <= size; i++ )); do
    for (( j = 1; j <= size; j++ )); do

        if [ "$i" == 1 ] || [ "$i" == "$size" ] || [ "$j" == 1 ] || [ "$j" == "$size" ]


         then
#Set the Cursor Position using tput cup

#You can move the cursor to a specific row and column using tput cup. Following
example positions the cursor at row i and column j.
            tput cup $i $j
            echo "*"
        fi
     done
done
Output
Concept of arrays
Array : An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
finite means data range must be defined.
ordered means data must be stored in continuous memory addresses.
homogenous means data must be of similar data type.
Declaration of Array :  
Syntax : data_type array_name[array_size];  
Example : int A[5];  
 Initialization of an Array :
Syntax : data-type array-name[size] = { list of values };
Example : int A[4]={ 67, 87, 56, 77 };
Program :  
#include<stdio.h>
#include<conio.h>
void main ()    
{    
    int i, j,temp;     
    int a[10] = { 1, 9, 7, 10, 2, 44, 11, 99, 20, 24};     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] > a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    printf("Sorted List ...\n");    
    for(i = 0; i<10; i++)    
    {    
        printf("%d ",a[i]);    
    }    
}  
Output : 

Two-Dimension Array : 
Declaration of two dimensional Array :
Syntax : data_type array_name[rows][columns];
Example : int A[4][3];  
 Initialisation of two dimensional Array : 
Syntax : data-type array-name[no of rows][no of columns] = { list of values };
Example : int A[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; 
Program :  
#include<stdio.h>
#include<conio.h>
void main()
{
  int m, n, c, d, first[10][10], second[10][10], sum[10][10];
  printf("Enter the number of rows and columns of matrix\n");
  scanf("%d%d", &m, &n);
  printf("Enter the elements of first matrix\n"); 
   for (c = 0; c < m; c++)
      for (d = 0; d < n; d++)
         scanf("%d", &first[c][d]);
   printf("Enter the elements of second matrix\n");
   for (c = 0; c < m; c++)
      for (d = 0 ; d < n; d++)
         scanf("%d", &second[c][d]);   
   printf("Sum of entered matrices:-\n");  
   for (c = 0; c < m; c++) {
      for (d = 0 ; d < n; d++) {
         sum[c][d] = first[c][d] + second[c][d];
         printf("%d\t", sum[c][d]);
   }
      printf("\n");
   }
}
Output : 

Write a C program to read and print elements of array


Program
 #include <stdio.h>  
void  main() 

    int arr[10];
    int i; 
   printf("\n\nRead and Print elements of an array:\n");   
   printf("Input 10 elements in the array :\n"); 
    for(i=0; i<10; i++) 
    { 
        printf("element - %d : ",i);
        scanf("%d", &arr[i]); 
    } 
    printf("\nElements in array are: "); 
    for(i=0; i<10; i++) 
    { 
        printf("%d  ", arr[i]); 
    }
    printf("\n");   
}
Output

Write a C program to find sum of all array elements


Program
 #include <stdio.h>
void main()
{
    int a[1000],i,n,sum=0;
    printf("Enter size of the array : ");
    scanf("%d",&n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0; i<n; i++)
    {
        
        sum+=a[i];
    }
     printf("sum of array is : %d",sum);
}
Output

Write a C program to find reverse of an array


Program
#include <stdio.h>
void main()
{
    int n, c, d, a[100], b[100];
    printf("Enter the number of elements in array\n");
    scanf("%d", &n);
    printf("Enter the array elements\n");
    for (c = 0; c < n ; c++)
    scanf("%d", &a[c]);   
    for (c = n - 1, d = 0; c >= 0; c--, d++)
        b[d] = a[c];  
    for (c = 0; c < n; c++)
        a[c] = b[c];
    printf("Reverse array is\n");
    for (c = 0; c < n; c++)
        printf("%d\n", a[c]);   
}
Output

Write a C program to check whether an element is present in an array or not


Program
#include <stdio.h>
void main()
{
    int a[10000],i,n,key;
    printf("Enter size of the  array : ");
    scanf("%d", &n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
     printf("Enter the key : ");
    scanf("%d", &key);
    
    for(i=0; i<n; i++)
    {
        if(a[i]==key)
        {
            printf("element found at\n ");
                     
        }
 
    }  
    printf("element  not  found");
}
Output

Write a C program to sort array elements in ascending order


Program
#include <stdio.h>

void main()
{
    int arr1[100];
    int n, i, j, tmp;
   
   
       printf("\n\nsort elements of array in ascending order :\n ");    
    printf("Input the size of array : ");
    scanf("%d", &n);

       printf("Input %d elements in the array :\n",n);


       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }

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


    {
        for(j=i+1; j<n; j++)
        {
            if(arr1[j] <arr1[i])
            {
                tmp = arr1[i];
                arr1[i] = arr1[j];
                arr1[j] = tmp;
            }
        }
    }
    printf("\nElements of array in sorted ascending order:\n");

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


    {
        printf("%d  ", arr1[i]);
    }
            printf("\n\n");
}

You might also like