Saturday, July 11, 2015


1. The if...else statements
1.1 if...fi statement
Syntax:
 if [ expression ]  
 then  
   Statement(s) to be executed if expression is true  
 fi  
or
 if [ expression ]; then  
   Statement(s) to be executed if expression is true   
 fi  

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 fi  
   
 if [ $a != $b ]  
 then  
   echo "a is not equal to b"  
 fi  

 $./test.sh  
 a is not equal to b  

1.2 if...else...fi statement
Syntax:
 if [ expression ]  
 then  
   Statement(s) to be executed if expression is true  
 else  
   Statement(s) to be executed if expression is not true  
 fi  

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 else  
   echo "a is not equal to b"  
 fi  

 $./test.sh  
 a is not equal to b  

1.3 if...elif...else...fi statement
Syntax:
 if [ expression 1 ]  
 then  
   Statement(s) to be executed if expression 1 is true  
 elif [ expression 2 ]  
 then  
   Statement(s) to be executed if expression 2 is true  
 elif [ expression 3 ]  
 then  
   Statement(s) to be executed if expression 3 is true  
 else  
   Statement(s) to be executed if no expression is true  
 fi  

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 elif [ $a -gt $b ]  
 then  
   echo "a is greater than b"  
 elif [ $a -lt $b ]  
 then  
   echo "a is less than b"  
 else  
   echo "None of the condition met"  
 fi  

 $./test.sh  
 a is less than b  

2. The case...esac 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  
    ;;  
 esac  

Ex1:
 #!/bin/sh  
   
 FRUIT="kiwi"  
   
 case "$FRUIT" in  
   "apple") echo "Apple pie is quite tasty."   
   ;;  
   "banana") echo "I like banana nut bread."   
   ;;  
   "kiwi") echo "New Zealand is famous for kiwi."   
   ;;  
 esac  

 $./test.sh  
 New Zealand is famous for kiwi.  

Ex2:
 #!/bin/sh  
 echo "Is it morning? Please answer yes or no"  
 read timeofday  
 case "$timeofday" in  
 yes | y | Yes | YES )  
      echo "Good Morning"  
      echo "Up bright and early this morning"  
      ;;  
 [nN]*)  
      echo "Good Afternoon"  
      ;;  
 *)  
      echo "Sorry, answer not recognized"  
      echo "Please answer yes or no"  
      exit 1  
      ;;  
 esac  
 exit 0  

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Lập trình hệ thống nhúng Linux . Powered by Luong Duy Ninh -