Fundamentals 14 min read

Master Bash Conditionals, Loops, and Signal Traps with Practical Examples

This guide provides a comprehensive walkthrough of Bash scripting fundamentals, covering conditional statements, various loop constructs, signal handling with trap, and a collection of useful one‑line scripts and visual examples for everyday tasks.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master Bash Conditionals, Loops, and Signal Traps with Practical Examples

1. Conditional Selection and Judgment

if statement syntax:

if condition1 ; then
  # code when true
elif condition2 ; then
  # code when true
else
  # code when all false
fi

Example: age validation and response based on numeric input.

# Determine age
#!/bin/bash
read -p "Please input your age: " age
if [[ $age =~ [^0-9] ]]; then
  echo "please input a int"
  exit 10
elif [ $age -ge 150 ]; then
  echo "your age is wrong"
  exit 20
elif [ $age -gt 18 ]; then
  echo "good good work,day day up"
else
  echo "good good study,day day up"
fi

Analysis: Checks for non‑numeric characters, then validates range and age thresholds.

case statement syntax:

case $var in
  PATTERN1) cmd ;; 
  PATTERN2) cmd ;; 
  *) cmd ;; 
esac

Example: yes/no input handling with pattern matching.

# Determine yes or no
#!/bin/bash
read -p "Please input yes or no: " ans
case $ans in
  [yY][eE][sS]|[yY]) echo yes ;;
  [nN][oO]|[nN]) echo no ;;
  *) echo false ;;
esac

2. Four Loop Types

for loop

Two forms:

# List iteration
for name in list; do
  # body
 done
# C‑style iteration
for ((exp1; exp2; exp3)); do
  # body
 done

Example: sum of 1..n.

# Sum 1+2+...+n
#!/bin/bash
read -p "Please input a positive integer: " num
if [[ $num =~ [^0-9] ]] || [ $num -eq 0 ]; then
  echo "input error"
  exit 10
else
  sum=0
  for i in $(seq 1 $num); do
    sum=$((sum + i))
  done
  echo $sum
fi

while loop

Syntax:

while condition; do
  # body
 done

Special form for reading a file line‑by‑line.

while read line; do
  # process $line
 done < /path/to/file

Example: sum of odd numbers up to 100.

# Sum odd numbers ≤100
sum=0
i=1
while [ $i -le 100 ]; do
  if [ $((i % 2)) -ne 0 ]; then
    let sum+=i
  fi
  let i++
done
echo "sum is $sum"

until loop

Runs until the condition becomes true (inverse of while).

until condition; do
  # body
 done

Example: monitor a user login and kill processes.

# Kill processes of user xiaoming when they log in
until pgrep -u xiaoming &>/dev/null; do
  sleep 0.5
done
pkill -9 -u xiaoming

select loop (menu)

Creates an interactive menu.

PS3="Please choose the menu: "
select menu in mifan huimian jiaozi babaozhou quit; do
  case $REPLY in
    1|4) echo "the price is 15" ;;
    2|3) echo "the price is 20" ;;
    5) break ;;
    *) echo "no the option" ;;
  esac
done

3. Loop Control Statements

continue [N]

skips to the next iteration of the N‑th outer loop; break [N] exits the N‑th outer loop.

# Sum odd numbers 1..100, skip 51
for i in {1..100}; do
  [ $i -eq 51 ] && continue
  [ $((i % 2)) -eq 1 ] && let sum+=i
 done
 echo sum=$sum

4. Shift Command in Loops

Shifts positional parameters left, removing the first argument.

# Create multiple users from arguments
#!/bin/bash
if [ $# -eq 0 ]; then
  echo "Please input a arg (e.g., $0 user1)"
  exit 1
else
  while [ -n "$1" ]; do
    useradd "$1" &>/dev/null
    shift
done
fi

5. Signal Trapping with trap

Define custom actions for signals.

# Prevent Ctrl+C from terminating a loop (signal 2)
#!/bin/bash
trap 'echo press ctrl+c' 2
for ((i=0;i<10;i++)); do
  sleep 1
  echo $i
done

Later restore default handling:

trap '' 2   # ignore SIGINT
# ...
trap '-' SIGINT   # restore default

6. Miscellaneous Bash Tips

Generate random alphanumeric string: cat /dev/urandom | tr -dc '[:alnum:]' | head -c 8 Generate random number: echo $RANDOM or range with arithmetic expansion.

Print colored text using ANSI escape codes.

7. Fun Small Scripts

9×9 Multiplication Table

#!/bin/bash
for a in {1..9}; do
  for b in $(seq 1 $a); do
    c=$((a*b))
    echo -e "${a}x${b}=${c}\t\c"
  done
  echo
 done

Colorful Isosceles Triangle

#!/bin/bash
read -p "Please input a num: " num
if [[ $num =~ [^0-9] ]]; then
  echo "input error"
else
  for i in $(seq 1 $num); do
    spaces=$((num-i))
    stars=$((2*i-1))
    printf "%*s" $spaces ""
    for ((k=1;k<=stars;k++)); do
      color=$((RANDOM%7+31))
      echo -ne "\033[1;${color};5m*\033[0m"
    done
    echo
  done
fi

Chessboard Pattern

#!/bin/bash
red="\033[1;41m  \033[0m"
yellow="\033[1;43m  \033[0m"
for i in {1..8}; do
  if (( i%2 == 0 )); then
    for _ in {1..4}; do echo -ne "${red}${yellow}"; done
  else
    for _ in {1..4}; do echo -ne "${yellow}${red}"; done
  fi
  echo
 done

These snippets illustrate core Bash constructs, practical patterns, and visual tricks useful for both learning and daily scripting tasks.

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.

BashexamplesShell scriptingLoopsConditionalstrap
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

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.