Fundamentals 11 min read

Master Bash Scripting: Conditional Statements, Loops, and Signal Traps Explained

This comprehensive guide walks you through Bash scripting fundamentals, covering conditional statements (if, case), four types of loops (for, while, until, select), loop control commands, signal trapping with trap, useful one‑liners, and a collection of fun mini‑scripts, all illustrated with clear examples and diagrams.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Bash Scripting: Conditional Statements, Loops, and Signal Traps Explained

Introduction

In Linux, Bash scripts are a foundational skill. Although advanced scripts can be complex, mastering basic syntax and techniques makes scripting approachable and powerful for automating repetitive tasks.

1. Conditional Statements

1.1 if

Syntax:

if <condition>; then
    # commands when true
elif <condition>; then
    # commands when true
else
    # commands when all conditions are false
fi

Example: Determine age input, validate numeric characters, ensure the value is between 18 and 150.

1.2 case

Syntax:

case $variable in
    pattern1) command ;; 
    pattern2) command ;; 
    *) command ;; 
esac

Example: Accept yes/no input, handling various capitalizations.

2. Loops

2.1 for

Two forms:

# Simple list iteration
for name in list; do
    # loop body
    done

# C‑style loop
for (( i=1; i<=n; i++ )); do
    # loop body
    done

Examples: Sum of numbers from 1 to n, sum of 1‑100, and generating a menu with select.

2.2 while

Syntax:

while <condition>; do
    # loop body
    done

Special usage: reading a file line‑by‑line with while read line; do … done < file. Example: Sum of all odd numbers below 100.

2.3 until

Syntax:

until <condition>; do
    # loop body
    done

Works opposite to while; rarely used.

2.4 select

Creates a simple menu:

select var in list; do
    # commands
    break
    done

Example: Display a price menu and capture user selection.

3. Loop Control Commands

continue [N]

skips the rest of the current loop iteration (or N‑th outer loop). break [N] exits the current loop (or N‑th outer loop). Example code shows their usage inside nested loops.

4. Shift Command

shift

removes the leftmost positional parameter, allowing scripts to process an arbitrary number of arguments, such as creating multiple users or printing a right‑angled triangle.

5. Return Values

true

always returns success, false always returns failure, and : is a no‑op that returns success. These can be used to build infinite loops, e.g., while true; do … done.

6. Signal Trapping (trap)

Syntax: trap 'command' SIGNAL Common signals: SIGHUP, SIGINT (Ctrl+C), SIGQUIT, SIGKILL, SIGTERM, SIGCONT, SIGSTOP. Examples demonstrate preventing Ctrl+C from terminating a script and restoring default behavior after a few iterations.

7. Handy One‑Liners

Generate random characters: cat /dev/urandom | tr -dc '[:alnum:]' | head -c 8 Generate random numbers: echo $RANDOM or echo $((RANDOM%7+31)) Print colored text:

echo -e "\033[31mred\033[0m"

8. Fun Mini‑Scripts

9×9 multiplication table

Colored isosceles triangle

ASCII chessboard

These examples illustrate how Bash can be used for both practical automation and creative scripting.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxBashsignal handlingShell scriptingLoopsConditionals
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.