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
if [ condition ]; then
commands
elif [ another_condition ]; then
other_commands
else
fallback_commands
fi1. 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
if [ "$USER" == "root" ]; then
echo "Running as root"
else
echo "Not root user"
fiCase Statement for Multi-Way Branching
case "$variable" in
pattern1) command1 ;;
pattern2) command2 ;;
*) default_command ;;
esacUseful for matching strings against patterns cleanly.
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:
for item in list; do
commands
done2. Syntax for numeric ranges:
for i in {1..5}; do
echo "Count: $i"
doneWhile Loop: Repeat Until Condition Fails
while [ condition ]; do
commands
doneExecutes as long as the condition is true.
Until Loop: Repeat Until Condition is True
until [ condition ]; do
commands
doneOpposite logic to while loop.
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:
function_name() {
commands
}3. Functions improve readability, testing, and reuse.
Calling Functions
1. Simply use:
function_name2. Passing Arguments to Functions
greet() {
echo "Hello, $1"
}
greet "Alice" # Outputs: Hello, Alice3. 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.
.png)