0% found this document useful (0 votes)
259 views

Shell Programming With Linux

The document provides an overview of common shell programming concepts in Linux including commands like echo, if/else statements, nested if statements, read statement, arrays, case statement, and a simple calculator program. It discusses using echo to display text, if/else statements for conditional execution, nested if statements to write if blocks within other blocks, reading user input with read, declaring and accessing arrays, the case statement for matching values, and a calculator program that performs basic math operations.

Uploaded by

harsh_786
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 PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
259 views

Shell Programming With Linux

The document provides an overview of common shell programming concepts in Linux including commands like echo, if/else statements, nested if statements, read statement, arrays, case statement, and a simple calculator program. It discusses using echo to display text, if/else statements for conditional execution, nested if statements to write if blocks within other blocks, reading user input with read, declaring and accessing arrays, the case statement for matching values, and a calculator program that performs basic math operations.

Uploaded by

harsh_786
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 PPT, PDF, TXT or read online on Scribd
You are on page 1/ 18

 

   Shell Programming with Linux

Shailendra Tiwari
"echo" Command

Use echo command to display text or value of variable.    


Syntax:
  echo [options] [string, variables...]
  Displays text or variables value on screen.          
Options
  -n Do not output the trailing new line.
  -e Enable interpretation of the following backslash
escaped characters in the strings:
  \a alert (bell)
  \b backspace
  \c suppress trailing new line
  \n new line
  \r carriage return
  \t horizontal tab
  \\ backslash
"if... else... fi" Statement
• If given condition is true then command1 is executed
otherwise command2 is executed.    
Syntax:
           if condition
           then
                       condition is zero (true - 0)
                       execute all commands up to else
statement
           else
                       if condition is not true then
                       execute all commands up to fi
           fi
"if... else... fi" Statement (cont..)
• Example:
• $ vi isnump_n
#!/bin/sh
# Script to see whether argument is positive or negative
if [ $# -eq 0 ]
thenecho "$0 : You must give/supply one integers"
exit 1
fi
if test $1 -gt 0
then
  echo "$1 number is positive"
else
  echo "$1 number is negative"
fi
"if... else... fi" Statement (cont..)
• Try it as follows:
$ chmod 755 isnump_n
$ isnump_n 5
5 number is positive
$ isnump_n -45
-45 number is negative
$ isnump_n
./ispos_n : You must give/supply one integers
$ isnump_n 0
0 number is negative
• Exercises:
1. If cost price and selling price of an item is input through
keyboard. Write a program to determine whether the seller
has made profit or incurred loss. Also determine how much
profit he made or loss he incurred.
2. Write a program to calculate overtime pay of an employee.
Overtime is paid at the rate of Rs. 40.00 per hour for every
hour worked above 30 hours. Determine that for how many
hours employee has worked under-time or over-time. Also
check for NO Overtime or Undertime working.
3. Write a program to find out whether the given number is an
odd or even number.
4. Input the marks obtained by a student in five different
subjects through keyboard. Find the total and percentage.
Using If .. Else statements determine the Grade of the
student. Also check if marks of any of the subject is less than
40 then “FAIL” should be displayed as result.
"Nested if-else-fi" Statement
• You can write the entire if-else construct within either the
body of the if statement of the body of an else statement.
This is called the nesting of ifs.
•   

Syntax:
                if condition
then
if condition
then
.....
..
do this
else
....
..
do this
fi
else
...
.....
do this
fi
Example:
$ vi nestedif.sh
osch=0
echo "1. Unix (Sun Os)"
echo "2. Linux (Red Hat)"
echo -n "Select your os choice [1 or 2]? "
read osch
if [ $osch -eq 1 ] ; then
     echo "You Pick up Unix (Sun Os)"
else #### nested if i.e. if within if ######
            
       if [ $osch -eq 2 ] ; then
             echo "You Pick up Linux (Red Hat)"
       else
             echo "What you don't like Unix/Linux OS."
       fi
fi
Run the above shell script as follows:

• $ chmod +x nestedif.sh
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 1
You Pick up Unix (Sun Os)
• $ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 2
You Pick up Linux (Red Hat)
• $ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 3
What you don't like Unix/Linux OS.
Exercises:  
1. Input basic salary of an employee through keyboard. Calculate
Gross_Salary, Deduction & Net_Salary with the following
conditions.
a.       If Salary is less than 5000, DA = 2.5% of basic, HRA = 5% of
basic, PF = 2.5% of basic, Tax = 750.
b.      If Salary is between 5000 and 15000, DA = 4% of basic, HRA =
10% of basic, PF = 3.75% of basic, Tax = 10%.
c.       If Salary is between 15000 and 30000, DA = 6.5% of basic,
HRA = 14% of basic, PF = 5% of basic, Tax = 12%.
d.      If Salary is between 30000 and 50000, DA = 8% of basic, HRA
= 15% of basic, PF = 6.25% of basic, Tax = 14%.
e.       If Salary is greater than 50000, DA = 10% of basic, HRA = 20%
of basic, PF = 7.5% of basic, Tax = 16.5%.
(GS = BASIC + DA + HRA, Deduct = PF + Tax & NS = GS – Deduct).
2. Input the marks obtained by a student in five different
subjects through keyboard. Find the total and percentage.
Using If .. Else statements determine the Grade of the
student. Also check if marks of any of the subject is less than
40 then “FAIL” should be displayed as result.

3. In the program (2), make the following modifications to check


the eligibility of the course for the student:
a.       If Chem >= 75, Phy >= 70 and Percent >= 80, then the Student is
Eligible for “Chemical Engg.” course.
b.      If Maths >= 85, Phy >= 70 and Percent >= 80, then the Student is
Eligible for “Electronics Engg.” course.
c.       If Maths >= 75, Phy >= 90 and Percent >= 70, then the Student is
Eligible for “Electrical Engg.” course.
d.      If Chem >= 85, Phy >= 70 and Percent >= 90, then the Student is
Eligible for “Medical” course.
e.       Otherwise “Eligible for any other Course”.
"read" Statement
• Use to get input (data from user) from keyboard and
store (data) to variable.    
Syntax:
read variable1, variable2,...variableN          
• Example:
$ vi sayH
#
# Script to read your name from key-board
#
echo "Your first name please:"
read fname
echo "Hello $fname, Lets be friend!"
Arrays
• Arrays can be declared in UNIX with the
declare keyword. To get the elements of the
array we have to enclose the array element
within { } prefixed with $.

Exercise:
• Write a shell script to sort an array in
ascending order.
#Script to find the maximum number from an array
# Declare the array of 5 subscripts to hold 5 numbers
#
declare nos[5]=(4 -1 2 66 10)
 #
# Prints the array
#
echo "Numbers in array:"
for (( i = 0; i <= 4; i++ ))
do
  echo ${nos[$i]}
done
#
# Finding maximum value
#
max=${nos[0]}
 
for (( i = 0; i <= 4 ; i++ ))
do
       if [ $max -lt ${nos[$i]} ]; then
           max=${nos[$i]}
       fi
   done
 
echo “The maximum value in an array is $max”
The case Statement
• The case statement is good alternative to Multilevel if-then-else-fi statement. It enables you to
match several values against one variable. Its easier to read and write.
Syntax:
•            case  $variable-name  in 
  pattern1)   command
                                ...
                                ..                               
command;;               
pattern2)   command                               
...                               
..                                
command;;               
patternN)   command                               
...                               
..                               
command;;               
*)             command                               
...                              

  ..                               
command;;          
esac
echo -n "Enter A, B, or C: "
read letter
case "$letter" in
  a|A)echo "You entered A"
  ;;
  b|B)echo "You entered B"
  ;;
  c|C)echo "You entered C"
  ;;
  *)echo "You did not enter A, B, or C"
  ;;
esac
• Note that esac is always required to indicate end
of case statement.
Simple Calculator
(
while [ $ != 'x' ]
do
echo "Welcome to calculator (x to quit)"
echo "Enter the first operand: "
read value1
echo "Enter an operator (+, -, *, /): "
read operator
echo "Enter the second operand: "
read value2
if [ " $ operator " = " + " ] ; then
answer=$(echo "scale=2;value1+value2" |bc);
elif [ " $ operator " = " - " ] ; then
answer=$(echo " scale=2;value1-value2" |bc);
elif [ " $ operator " = " / " ] ; then
answer=$(echo "scale=2;value1/value2" |bc);
elif [ " $ operator " = " * " ] ; then
answer=$(echo "scale=2;value1*value2" |bc);
elif [ " $ operator " = " % " ] ; then
answer=$(echo "scale=2;value1%value2" |bc);
fi
echo "Answer: $value1 $operator $value2 = $answer";
done
)

You might also like