Linux Shell Scripting

Linux Shell Scripting Tutorial – Module 3: Operators & Conditional Statements

Module 3: Operators & Conditional Statements

In this module, you will learn how to use operators and conditional statements
to control the flow of your shell scripts.
These tools allow scripts to make decisions based on conditions.

✅ Arithmetic Operators

  • Bash supports arithmetic using $(( expression )).
  • Common operators: +, -, *, /, %.

#!/bin/bash
a=10
b=3
echo "Addition: $((a+b))"
echo "Division: $((a/b))"
echo "Remainder: $((a%b))"
  

Output:


Addition: 13
Division: 3
Remainder: 1
  

✅ Comparison Operators (Numbers)

  • -eq → Equal
  • -ne → Not equal
  • -gt → Greater than
  • -lt → Less than
  • -ge → Greater than or equal
  • -le → Less than or equal

#!/bin/bash
x=20
y=15
if [ $x -gt $y ]
then
  echo "$x is greater than $y"
fi
  

✅ String Comparison

  • = → Equal
  • != → Not equal
  • -z → String is empty
  • -n → String is not empty

#!/bin/bash
str1="hello"
str2="world"
if [ "$str1" != "$str2" ]
then
  echo "Strings are different"
fi
  

✅ Logical Operators

  • -a → AND
  • -o → OR
  • ! → NOT
  • Modern Bash also supports && and ||.

#!/bin/bash
num=7
if [ $num -gt 0 -a $num -lt 10 ]
then
  echo "Number is between 1 and 9"
fi
  

✅ If-Else Statements


#!/bin/bash
echo "Enter your age:"
read age

if [ $age -ge 18 ]
then
  echo "You are eligible to vote."
else
  echo "Sorry, you are underage."
fi
  

✅ If-Elif-Else Ladder


#!/bin/bash
echo "Enter a number:"
read n

if [ $n -gt 0 ]
then
  echo "Positive"
elif [ $n -lt 0 ]
then
  echo "Negative"
else
  echo "Zero"
fi
  

✅ Nested If


#!/bin/bash
echo "Enter a number:"
read n

if [ $n -gt 0 ]
then
  if [ $((n%2)) -eq 0 ]
  then
    echo "Positive Even"
  else
    echo "Positive Odd"
  fi
fi
  

✅ Summary

  • Arithmetic operators perform calculations using $(( )).
  • Comparison operators check numeric conditions like -eq, -gt.
  • Strings can be compared with =, !=, -z, -n.
  • Logical operators allow multiple conditions.
  • if, if-else, elif, and nested if enable decision-making in scripts.

✅ By the end of this module, you can make decisions in scripts using operators and conditional statements.

Leave a Reply

Your email address will not be published. Required fields are marked *