Control Flow Constructs in Shell Scripting
Multi-Branch Conditional Logic
Syntax
if <condition1>; then
commands1
elif <condition2>; then
commands2
...
else
commandsN
fi
The structure evaluates conditions sequentiallly. If the first condition fails, it proceeds to the next. If none match, the else block executes. Once a condition matches, its associated commands run and the structure exits.
Example 1: Comparing Two Numbers
This script prompts for two inetgers and compares them:
#!/bin/bash
read -p "Enter two numbers: " num1 num2
if [ $num1 -eq $num2 ]; then
echo "$num1 equals $num2"
elif [ $num1 -gt $num2 ]; then
echo "$num1 greater than $num2"
elif [ $num1 -lt $num2 ]; then
echo "$num1 less than $num2"
else
echo "Error"
fi
Example 2: Grading Based on Score
This script asigns grades based on numerical scores:
#!/bin/bash
read -p "Enter score: " score
if [ -z "$score" ]; then
echo "Score cannot be empty"
exit 1
elif [[ $score -lt 0 || $score -gt 100 ]]; then
echo "Score must be between 0 and 100"
exit 2
elif [ $score -ge 85 ]; then
echo "A"
elif [ $score -ge 70 ]; then
echo "B"
elif [ $score -ge 60 ]; then
echo "C"
else
echo "D"
fi
Program Termination
Use exit to terminate a script and return an exit status code.
Syntax
exit status
Exit codes:
0: Successful execution- Non-zero: Error occurred
Example Usage
#!/bin/bash
echo "Hello World"
echo $?
nonexistent_command
echo $?
exit 100
Case Statement
Syntax
case variable in
value1)
commands1
;;
value2)
commands2
;;
*)
default_commands
;;
esac
Each value is matched against the variable. Execution stops at ;;. If no match occurs, the * clause runs.
Example 1: Character Type Detection
#!/bin/bash
read -p "Enter a character: " char
if [ -z "$char" ]; then
echo "Input cannot be empty"
exit 2
fi
if [ $(expr length "$char") -ne 1 ]; then
echo "Input must be one character"
exit 3
fi
case "$char" in
[a-z]|[A-Z])
echo "It's a letter"
;;
[0-9])
echo "It's a digit"
;;
*)
echo "It's another character"
;;
esac
Example 2: Grade Classification Using Case
#!/bin/bash
read -p "Enter score: " score
case $score in
8[5-9]|9[0-9]|100)
echo "A"
;;
7[0-9]|8[0-4])
echo "B"
;;
6[0-9])
echo "C"
;;
*)
echo "D"
;;
esac
Practical Exercise: Rsync Management Script
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 {start|stop|restart}"
exit 1
fi
case "$1" in
start)
/usr/bin/rsync --daemon
sleep 1
if [ `ss -lntup|grep rsync|wc -l` -ge 1 ]; then
echo "rsync started"
exit 0
fi
;;
stop)
killall rsync &>/dev/null
sleep 1
if [ `ss -lntup|grep rsync|wc -l` -eq 0 ]; then
echo "rsync stopped"
exit 0
fi
;;
restart)
if [ `ss -lntup|grep rsync|wc -l` -ge 1 ]; then
killall rsync &>/dev/null
sleep 1
fi
/usr/bin/rsync --daemon
sleep 1
echo "rsync restarted"
exit 0
;;
*)
echo "Usage: $0 {start|stop|restart}"
;;
esac