Shell Scripting Lesson 7 - If else Statement

As you know if else statements are used as control statements. When you make decision based on a value of variable, you should use if else statement. If else statements are fundamental control statements.

In shell Scripting, Basic if statements should be written as follows.
if [ expression ]
then
   Execution steps, if condition is true
fi 

 if Statements are starting from if keyword and ends with fi keyword. See below Example.
num1=5
num2=10
if [ $num1 == $num2 ]
then
   echo "I am inside the if block"
fi 


 you can write if else statements as seen in the below example. if else statements are same as if statements.
if [ expression ]
then
   Execution steps, if condition is true
else
   Execution steps, if condition is false
fi

Let's go with my above Example.If I want to check condition is true or false, we can write If statements with else part. In my example I have checked the value of variable num1 is equal to 10. If it is true, if part is running. if false, other part will run. :)
num1=5
if [ $num1 == 10 ]
then
   echo "I am inside the if block" 
else
   echo "I am inside the else block" 
 fi 

sLet's do more with if else statements. If you want to check condition with two or more values, we can write if elseif statements.
if [ expression 1 ]
then
   checks expression 1 is true
elif [ expression 2 ]
then
   checks expression 2 is true
else
   both expression 1 and expression 2 are false
fi


Switch Case Statements
switch case statements are starting from case and ends with esac. See the Below Syntax.
case word in
  case1)
     case1 matches
     ;;
  case2)
     case2 matches
     ;;
  case3)
     case3 matches
     ;;
esac

In above syntax, It maches thress cases. if one of above case is matched, codes are in below the matched case are executed.
tutorial="shell"
case tutorial in
     "shell")
          echo "shell scripting tutorials"
          ;;
     "awk")
          echo "awk tutorials"
          ;;
     "sed")
          echo "sed tutorials"
          ;;
esac

This is End of if else if tutorial !

0 comments:

Post a Comment

Ask anything about this Tutorial.