Lesson 7 / 8
Module 4Lesson 1⏱ 60 min study

Lesson 7: Bash Scripting Masterclass: Variables, Arguments, Conditional Logic & Loops

Transition from command-line user to systems engineer: learn the shebang, execution permissions, environment and local variables, positional parameters ($1, $2), test operators, and loop constructs.

✦ Key Architectural Takeaways
  • •A Bash script begins with a shebang line (#!/bin/bash), instructing the kernel which interpreter to invoke when executing the file.
  • •Executable permissions must be granted using 'chmod +x script.sh' before a script can be invoked directly via ./script.sh.
  • •Variable assignment requires no spaces around the equals sign (e.g., NAME='Linux'); variables are expanded using the dollar prefix ($NAME).
  • •Conditional evaluation uses the test command or bracket syntax [ condition ], with dedicated flags for numbers (-eq, -lt, -gt) and strings (=, !=, -z).
  • •Bash supports three primary looping paradigms: 'for' loops (iterating over lists or ranges), 'while' loops (executing while true), and 'until' loops (executing until true).

1. The Anatomy of a Production Bash Script

A Bash script is an executable plaintext file containing a sequence of commands executed sequentially by the shell interpreter.

BASHSYSTEM SCHEMATIC
#!/bin/bash
# ==============================================================================
# Script Name : system_probe.sh
# Purpose     : Display fundamental workstation metrics and kernel version
# Author      : Anupam Baral
# ==============================================================================

# 1. Variable Assignment (Notice: NO spaces around '=')
AUTHOR="Anupam"
HOST_NAME=$(hostname)
KERNEL_VER=$(uname -r)
CURRENT_DATE=$(date +"%Y-%m-%d %H:%M:%S")

# 2. Output Formatting
echo "=========================================="
echo " System Diagnostic Report"
echo " Generated on : ${CURRENT_DATE}"
echo " Hostname     : ${HOST_NAME}"
echo " Kernel       : ${KERNEL_VER}"
echo " Engineer     : ${AUTHOR}"
echo "=========================================="

Making the Script Executable

BASHSYSTEM SCHEMATIC
# Grant execution permissions to the owner
chmod +x system_probe.sh

# Execute the script from the current working directory
./system_probe.sh
§

2. Interactive Prompts & Positional Parameters

Scripts can accept dynamic inputs either via positional arguments passed on the command line or via interactive user prompts using read.

BASHSYSTEM SCHEMATIC
#!/bin/bash
# Demonstrating command-line arguments and interactive reading

# Positional Parameters:
# $0 = script name, $1 = first argument, $2 = second argument, $# = total argument count
echo "Executing Script: $0"
echo "Total Arguments Passed: $#"

if [ $# -ge 2 ]; then
    NUM1=$1
    NUM2=$2
else
    # Interactive fallback if arguments are not provided
    read -p "Enter first integer: " NUM1
    read -p "Enter second integer: " NUM2
fi

# Arithmetic Expansion using $(( ... ))
SUM=$((NUM1 + NUM2))
PRODUCT=$((NUM1 * NUM2))

echo "The arithmetic sum of $NUM1 + $NUM2 is: $SUM"
echo "The arithmetic product of $NUM1 * $NUM2 is: $PRODUCT"
§

3. Conditional Branching: if, elif, else

In Bash, conditional statements test exit statuses or file/string/integer conditions:

BASHSYSTEM SCHEMATIC
#!/bin/bash

read -p "Enter a path to inspect: " TARGET_PATH

# File & Directory Test Operators:
# -e : exists | -f : regular file | -d : directory | -r : readable | -w : writable
if [ -d "$TARGET_PATH" ]; then
    echo "SUCCESS: '$TARGET_PATH' is a valid directory."
    echo "Directory contents count: $(ls -1 "$TARGET_PATH" | wc -l)"
elif [ -f "$TARGET_PATH" ]; then
    echo "SUCCESS: '$TARGET_PATH' is a regular file."
    echo "File size in bytes: $(stat -c%s "$TARGET_PATH")"
else
    echo "ERROR: '$TARGET_PATH' does not exist or is a special device node."
fi

Comparison Operator Reference

Evaluation TypeOperatorsExample Syntax
Integer Comparison-eq (equal), -ne (not equal), -lt (less than), -le (less/equal), -gt (greater than), -ge (greater/equal)[ "$COUNT" -lt 100 ]
String Comparison= (equal), != (not equal), -z (string is empty), -n (string is not empty)[ "$NAME" = "admin" ]
Logical Boolean&& (AND), `
(OR), !` (NOT)[ -f "$FILE" ] && [ -r "$FILE" ]
§

4. Looping Paradigms: for, while, and until

BASHSYSTEM SCHEMATIC
#!/bin/bash

echo "--- 1. For Loop: Iterating over a sequence ---"
for i in {1..5}; do
    echo "Step number: $i"
done

echo -e "
--- 2. For Loop: Processing all .txt files in directory ---"
for file in *.txt; do
    # Protect against empty matches if no .txt files exist
    [ -e "$file" ] || continue
    echo "Processing file: $file (Lines: $(wc -l < "$file"))"
done

echo -e "
--- 3. While Loop: Counter with numeric test ---"
COUNTER=1
while [ $COUNTER -le 3 ]; do
    echo "While counter is: $COUNTER"
    COUNTER=$((COUNTER + 1))
done

echo -e "
--- 4. Until Loop: Repeats UNTIL condition becomes true ---"
COUNTDOWN=3
until [ $COUNTDOWN -le 0 ]; do
    echo "T-minus $COUNTDOWN..."
    COUNTDOWN=$((COUNTDOWN - 1))
done
echo "Liftoff!"