02 - Flow Control in Linux
I am an aspiring DevOps Engineer proficient with containers and container orchestration tools like Docker, Kubernetes along with experienced in Infrastructure as code tools and Configuration as code tools, Terraform, Ansible. Well-versed in CICD tool - Jenkins. Have hands-on experience with various AWS and Azure services. I really enjoy learning new things and connecting with people across a range of industries, so don't hesitate to reach out if you'd like to get in touch.
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
ifStatementif-elseStatementif-elif-elseStatement
if Statement
The
ifstatement 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-elsestatement 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-elsestatement 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:
forandwhile.
For Loop
forloops 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 donevariable: 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" doneIterating Over Numbers:
#!/bin/bash for num in 1 2 3 4 5; do echo "Number: $num" doneUsing a Range of Numbers:
#!/bin/bash for i in {1..5}; do echo "Count: $i" doneUsing a Range with Step:
#!/bin/bash for i in {1..10..2}; do echo "Step: $i" doneIterate through list of files from the output of the
lscommand:#!/bin/bash for file in $(ls) do echo Line count of $file is $(cat $file | wc -l) doneIterating Over Files:
#!/bin/bash for file in *.txt; do echo "Processing $file" doneIterate 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 doneC-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 donecondition: 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
whileLoop:#!/bin/bash count=1 while [ $count -le 5 ]; do echo "Count: $count" ((count++)) doneReading a File Line by Line:
#!/bin/bash filename="example.txt" while read -r line; do echo "Line: $line" done < "$filename"The
read -rcommand 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 doneLoop with a Condition:
#!/bin/bash num=10 while [ $num -gt 0 ]; do echo "Countdown: $num" ((num--)) done
Case Statements
The
casestatement in shell scripting is used to simplify the evaluation of multiple conditions.It is a more concise and readable alternative to
if-elif-elsestructures when need to compare a single variable or expression against multiple patterns.Syntax:
case variable in pattern1) commands ;; pattern2) commands ;; *) default_commands ;; esacvariable: 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" ;; esacFile 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." ;; esacDay 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