USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Conditional Logic, Loops, and Functions for Modular Scripts

Lesson 22/31 | Study Time: 25 Min

Writing modular and maintainable bash scripts requires effective use of conditional logic, loops, and functions. These fundamental programming constructs enable scripts to make decisions, repeat tasks, and organize code into reusable blocks, enhancing clarity and scalability. 

Conditional Logic in Bash

Using conditional logic effectively allows scripts to execute different paths based on evaluated conditions. The list below demonstrates how to implement if statements, elif chains, and case statements.

Purpose of Conditional Statements: It allow scripts to execute different commands based on evaluated conditions (true or false). Common constructs: if-then-else, elif, and case.

Basic if Statement Syntax

bash
if [ condition ]; then
commands
elif [ another_condition ]; then
other_commands
else
fallback_commands
fi


1. Conditions use test operators such as -eq (equal), -lt (less than), string comparisons, or command exit status.

2. Always close with fi.


Example: Simple Conditional Check

bash
if [ "$USER" == "root" ]; then
echo "Running as root"
else
echo "Not root user"
fi


Case Statement for Multi-Way Branching

bash
case "$variable" in
pattern1) command1 ;;
pattern2) command2 ;;
*) default_command ;;
esac


Useful for matching strings against patterns cleanly.

Loops in Bash

Using loops enables Bash scripts to automate repetitive tasks efficiently. The following sections explain syntax and examples for for, while, and until loops.


For Loop: Iterate Over Items or Ranges


1. Syntax for list iteration:

bash
for item in list; do
commands
done


2. Syntax for numeric ranges:

bash
for i in {1..5}; do
echo "Count: $i"
done


While Loop: Repeat Until Condition Fails

bash
while [ condition ]; do
commands
done

Executes as long as the condition is true.


Until Loop: Repeat Until Condition is True

bash
until [ condition ]; do
commands
done

Opposite logic to while loop.

Functions for Modularity

Functions provide a structured way to organize and reuse code in Bash scripts. The list below demonstrates how to define functions, pass arguments, and return values effectively.


Defining Functions

1. Group commands into reusable blocks.

2. Basic syntax:

bash
function_name() {
commands
}


3. Functions improve readability, testing, and reuse.


Calling Functions


1. Simply use:

bash
function_name


2. Passing Arguments to Functions

bash
greet() {
echo "Hello, $1"
}
greet "Alice" # Outputs: Hello, Alice


3. Access passed parameters with $1, $2, etc.


Returning Values


1. Use return for numeric exit status (0-255).

2. Output strings via echo and capture with command substitution.


Andrew Foster

Andrew Foster

Product Designer
Profile

Class Sessions

1- Linux Security Model Overview 2- Kernel-Level Security Features (Namespaces, Capabilities, SELinux, AppArmor) 3- Linux File System Permissions and Extended Attributes (Xattr) 4- Secure User and Group Management Fundamentals 5- Best Practices for Sudo Configuration and Privilege Escalation Control 6- Disabling Unneeded Services and Configuring Secure Boot 7- Firewall Setup: Iptables/Nftables Basics and Advanced Rule Creation 8- Securing SSH: Key Management, Configuration, and Tunneling 9- Mandatory Access Control (SELinux/AppArmor Detailed Configuration) 10- Deployment of PAM for Enhanced Authentication 11- Linux Network Namespaces and Container Isolation Basics 12- TLS/SSL Configuration for Linux Services 13- VPN Setup for Secure Remote Access (OpenVPN, WireGuard) 14- Cryptographic Tools: GPG Encryption, Hashing Utilities, and Key Management 15- Intrusion Detection Systems and Log Monitoring Tools Overview 16- Linux Audit Framework (Auditd) Configuration and Log Analysis 17- Using Syslog, Journald, and Centralized Logging Solutions 18- File Integrity Monitoring with AIDE And Tripwire 19- Compliance Frameworks Introduction (PCI DSS, GDPR, HIPAA) 20- Incident Response Preparation and Forensic Readiness Basics 21- Bash Scripting Best Practices for Security and Automation 22- Conditional Logic, Loops, and Functions for Modular Scripts 23- Handling Errors, Signals, and Debugging Scripts Effectively 24- Automating User and Permission Audits with Scripts 25- Integrating Shell Scripts with System Tools (Cron Jobs, Systemd Timers) 26- Automating Log Analysis and Alerting Via Scripting 27- Writing Scripts for Automated Patch and Vulnerability Management 28- Automating Firewall and SSH Key Rotation Policies 29- Integrating Shell Scripts with Security Scanning Tools (Lynis, OpenVAS) 30- Case Studies on Automated Incident Detection and Response 31- Using Open-Source Tools for Orchestration with Scripting