Operations 17 min read

Master Bash Conditionals, Loops, and Signal Traps: Practical Scripts Explained

This article provides a comprehensive guide to Bash scripting, covering conditional statements (if/elif/else), case selections, various loop constructs (for, while, until, select), loop control commands, parameter shifting, signal trapping with trap, and includes numerous practical code examples with detailed analysis.

Open Source Linux
Open Source Linux
Open Source Linux
Master Bash Conditionals, Loops, and Signal Traps: Practical Scripts Explained

Condition Selection and Judgment

1. if statement

Usage format:

if condition1 ; then
  # commands for true condition
elif condition2 ; then
  # commands for true condition
else
  # commands when all conditions are false
fi

The script evaluates each condition sequentially; the first true condition executes its block and then exits the if structure.

Example – Determine age:

# 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: The script first checks for non‑numeric characters, then validates the range, and finally distinguishes adults from younger users.

Example – Determine score:

# Determine score
#!/bin/bash
read -p "Please input your score: " score
if [[ $score =~ [^0-9] ]]; then
  echo "please input a int"
  exit 10
elif [ $score -gt 100 ]; then
  echo "Your score is wrong"
  exit 20
elif [ $score -ge 85 ]; then
  echo "Your score is very good"
elif [ $score -ge 60 ]; then
  echo "Your score is soso"
else
  echo "You are loser"
fi

Analysis: The script validates numeric input, then checks for out‑of‑range values, and finally categorises the score into different performance levels.

2. case statement

Usage format:

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

The case command supports glob‑style patterns such as *, ?, [], and a|b.

Example – Yes/No decision:

# 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

Analysis: Accepts various capitalisations of “yes” and “no”; any other input yields “false”.

Four Loop Constructs

1. for loop

Usage formats:

# Iterate over a list
for name in list; do
  # loop body
 done

# C‑style for loop
for (( exp1; exp2; exp3 )); do
  # loop body
 done

Example – Sum of 1 to n:

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

Analysis: Validates the input, then iterates from 1 to the entered number, accumulating the total.

2. while loop

Usage format:

while condition; do
  # loop body
 done

Special usage – 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 of odd numbers up to 100
#!/bin/bash
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"

Analysis: Iterates while the counter is ≤ 100, adds the number to the sum only when it is odd.

3. until loop

Usage format (inverse of while):

until condition; do
  # loop body
 done

Example – Monitor a user and kill the session when they log in:

# Monitor user xiaoming
until pgrep -u xiaoming &>/dev/null; do
  sleep 0.5
 done
pkill -9 -u xiaoming

Analysis: Checks every half second; when the user appears, the script terminates all processes belonging to that user.

4. select loop (menu)

Usage format:

select var in list; do
  # commands for chosen item
 done

Example – Simple menu with price display:

# Menu example
#!/bin/bash
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

Analysis: Displays numbered options, executes the corresponding case branch, and exits when the user selects “quit”.

Loop Control Statements

Commands: continue [N] – skip the rest of the current loop iteration and start the next one (N specifies the nesting level). break [N] – exit the loop early (N specifies the nesting level).

Example – Sum of odd numbers excluding 51:

# Sum 1+3+...+49+53+...+100
#!/bin/bash
sum=0
for i in {1..100}; do
  [ $i -eq 51 ] && continue
  [ $((i % 2)) -eq 1 ] && let sum+=i
 done
 echo sum=$sum

Analysis: Skips the iteration when i equals 51, otherwise adds odd numbers to the sum.

Parameter Shifting with shift

shift

removes the leftmost positional parameter, moving the remaining ones one position to the left.

Example – Create multiple users from arguments:

# Create users from arguments
#!/bin/bash
if [ $# -eq 0 ]; then
  echo "Please input at least one username"
  exit 1
else
  while [ -n "$1" ]; do
    useradd "$1" &>/dev/null
    shift
  done
fi

Analysis: Loops over all supplied arguments, creating a user for each name.

Signal Trapping with trap

Format:

trap 'command' SIGNAL   # Execute command when SIGNAL is received
trap '' SIGNAL          # Ignore SIGNAL
trap - SIGNAL          # Reset SIGNAL to default behavior
trap -p                 # List current traps

Common signals:

SIGHUP – reload configuration

SIGINT – interrupt (Ctrl+C)

SIGQUIT – quit (Ctrl+\)

SIGKILL – force kill (cannot be trapped)

SIGTERM – termination request

SIGCONT – continue after stop

SIGSTOP – stop (cannot be trapped)

Example – Prevent Ctrl+C from terminating a counting loop:

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

Analysis: The script catches signal 2 (SIGINT) and prints a message instead of exiting.

Example – Allow Ctrl+C after the first three iterations:

# Allow termination after three iterations
#!/bin/bash
trap '' 2               # Ignore SIGINT
for ((i=0;i<3;i++)); do
  sleep 1
  echo $i
 done
trap '-' SIGINT        # Restore default handling
for ((i=3;i<10;i++)); do
  sleep 1
  echo $i
 done

Analysis: The first loop ignores SIGINT; after it finishes, the trap is removed so the script can be stopped with Ctrl+C.

Additional Handy Bash Snippets

Random character generation

# Generate 8 random alphanumeric characters
cat /dev/urandom | tr -dc '[:alnum:]' | head -c 8

Random number

# Generate a random number between 0 and 6
echo $((RANDOM % 7))
# Generate a random number between 31 and 37
echo $((RANDOM % 7 + 31))

Colored output

# Red text
echo -e "\033[31malong\033[0m"
# Bold red text
echo -e "\033[1;31malong\033[0m"
# Red background
echo -e "\033[41malong\033[0m"
# Blinking red text
echo -e "\033[31;5malong\033[0m"

9×9 multiplication table

# 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

# Colorful 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
    stars=$((2*i-1))
    for _ in $(seq 1 $((num-i))); do echo -n " "; done
    for _ in $(seq 1 $stars); do
      color=$((RANDOM%7+31))
      echo -ne "\033[1;${color};5m*\033[0m"
    done
    echo
  done
fi

Chessboard pattern

# 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 -n -e "${red}${yellow}"; done
  else
    for _ in {1..4}; do echo -n -e "${yellow}${red}"; done
  fi
  echo
 done
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.

Bashsignal handlingShell scriptingLoopsConditionals
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

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.