02 - Flow Control in Linux
Conditional Logic
- Conditional logic in shell scripting is used to execute commands based on specific conditions. This allows scripts to make decisions, enabling dynamic and flexible execution paths.
Types of Conditional Statements
if
Statementif-else
Statementif-elif-else
Statement
if
Statement
The
if
statement runs a block of commands if the condition evaluates to true.The condition is enclosed under a pair of square brackets
[ ]
.if [ condition ]; then commands fi
if-else
Statement
The
if-else
statement adds an alternative set of commands to run when the condition is false.if [ condition ]; then commands_if_true else commands_if_false fi
if-elif-else
Statement
The
if-elif-else
statement is used for multiple conditions.if [ condition1 ]; then commands_if_condition1 elif [ condition2 ]; then commands_if_condition2 else commands_if_all_fail fi
Note:
Comparison statements or conditions must be enclosed within a pair of square brackets
[ ]
, and there should be at least one space between the brackets and the statement as well as between the operator and the values on either sides.[ string1 = string2 ]
We can also use double pair of square brackets
[[ ]]
to specify the conditions but it only works in bash:[[ string1 = string2 ]]
- This works similar to above and its an enhanced version and supports additional operations like matching patterns using expressions.
AND (
&&
) and OR (||
) Operators are there to combine multiple conditions:Below are some file-level operators:
Use
-z <variable>
to check for command line argument.if [ -z $month ]; then # this checks if the $month is empty echo "No month number given" fi
Loops
The loop in shell scripting is used to iterate over a sequence of items, performing a set of commands for each item.
There are 2 types of loops:
for
andwhile
.
For Loop
for
loops is used when you want to run:Same command multiple times.
Iterate through files
Iterate through lines within a file
Iterate through the output of a command
Syntax:
for variable in list; do commands done
variable
: A placeholder that takes the value of each item in the list during iteration / gives the value of current iteration.list
: A sequence of items (e.g., numbers, strings, or file names).commands
: Commands to execute for each item in the list.
Break and Continue:
break
: Exit the loop immediately.continue
: Skip the current iteration and proceed to the next.
Ways to use for loop
Iterating Over a List of Words:
#!/bin/bash for item in apple orange banana; do echo "Fruit: $item" done
Iterating Over Numbers:
#!/bin/bash for num in 1 2 3 4 5; do echo "Number: $num" done
Using a Range of Numbers:
#!/bin/bash for i in {1..5}; do echo "Count: $i" done
Using a Range with Step:
#!/bin/bash for i in {1..10..2}; do echo "Step: $i" done
Iterate through list of files from the output of the
ls
command:#!/bin/bash for file in $(ls) do echo Line count of $file is $(cat $file | wc -l) done
Iterating Over Files:
#!/bin/bash for file in *.txt; do echo "Processing $file" done
Iterate through list of packages stored in a file and installs them one by one:
#!/bin/bash for package in $(cat install-packages.txt) do sudo apt-get –y install $package done
C-Style for Loop:
#!/bin/bash for ((i=1; i<=5; i++)); do # need to use double parentheses echo "Value: $i" done
While Loop
While loop works same as the for loop except that it executes the loop as long as the condition is true.
It is ideal for situations where the number of iterations is not predetermined and depends on dynamic conditions.
Syntax:
while [ condition ]; do commands done
condition
: A condition that determines whether the loop should continue.commands
: The block of code to be executed repeatedly as long as the condition is true.
Break and Continue:
break
: Exit the loop immediately.continue
: Skip the current iteration and proceed to the next.
Ways to use while loop
Basic
while
Loop:#!/bin/bash count=1 while [ $count -le 5 ]; do echo "Count: $count" ((count++)) done
Reading a File Line by Line:
#!/bin/bash filename="example.txt" while read -r line; do echo "Line: $line" done < "$filename"
The
read -r
command reads each line from the file.The
< "$filename"
redirects the file's contents into the loop.
Infinite Loop:
#!/bin/bash while true; do echo "Press Ctrl+C to stop" sleep 1 done
Loop with a Condition:
#!/bin/bash num=10 while [ $num -gt 0 ]; do echo "Countdown: $num" ((num--)) done
Case Statements
The
case
statement in shell scripting is used to simplify the evaluation of multiple conditions.It is a more concise and readable alternative to
if-elif-else
structures when need to compare a single variable or expression against multiple patterns.Syntax:
case variable in pattern1) commands ;; pattern2) commands ;; *) default_commands ;; esac
variable
: The value to be evaluated.pattern1, pattern2, ...
: Patterns to match the variable's value.*)
: The default case, executed if no patterns match.;;
: Indicates the end of a case.
Ways to use case statement
Simple Menu:
#!/bin/bash echo "Enter a number (1-3):" # can also be written as: read num # read -p "Enter a number (1-3):" num case $num in 1) echo "You selected 1" ;; 2) echo "You selected 2" ;; 3) echo "You selected 3" ;; *) echo "Invalid selection" ;; esac
File Type Check:
#!/bin/bash file="example.txt" case $file in *.txt) echo "This is a text file." ;; *.jpg | *.png) echo "This is an image file." ;; *.sh) echo "This is a shell script." ;; *) echo "Unknown file type." ;; esac
Day of the Week:
#!/bin/bash day=$(date +%A) case $day in Monday | Tuesday | Wednesday | Thursday | Friday) echo "It's a weekday." ;; Saturday | Sunday) echo "It's the weekend!" ;; *) echo "Unknown day." ;; esac