Operations 16 min read

Comprehensive Bash Scripting Guide: Conditionals, Loops, and Signal Traps

This article provides a detailed Bash scripting tutorial covering conditional statements (if/elif/else, case), various loop constructs (for, while, until, select), control commands (break, continue, shift), signal handling with trap, and several practical example scripts such as a multiplication table, colored triangle, and chessboard pattern.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Bash Scripting Guide: Conditionals, Loops, and Signal Traps

1. Conditional Selection and Judgment

1.1 if statement

Usage format:

if condition1 ; then
  # code for true branch
elif condition2 ; then
  # code for second true branch
else
  # code when all conditions are false
fi

Example: age validation script that checks for non‑numeric input, out‑of‑range values, and age thresholds.

#判断年纪
#!/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 validates that the input contains only digits, then checks whether the age is less than 150 and greater than 18.

Another example validates a score with similar logic.

#判断分数
#!/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 checks for non‑numeric characters, then validates the score range.

1.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 .

#判断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: the script treats any case‑insensitive form of "yes" as yes, any form of "no" as no, and all other inputs as false.

2. Loops

2.1 for loop

Two common forms:

# form 1
for name in list; do
  # loop body
 done
# form 2 (C‑style)
for (( exp1; exp2; exp3 )); do
  # loop body
 done

Example: calculate the sum of numbers from 1 to n.

#求出(1+2+...+n)的总和
sum=0
read -p "Please input a positive integer: " num
if [[ $num =~ [^0-9] ]] || [ $num -eq 0 ]; then
  echo "input error"
else
  for i in `seq 1 $num`; do
    sum=$[ $sum + $i ]
  done
  echo $sum
fi
unset zhi

Analysis: after validating the input, the script iterates from 1 to the entered number, accumulating the total.

Another example uses a C‑style for loop to sum only odd numbers up to 100.

#求出(1+3+...+100)的总和
for (( i=1, sum=0; i<=100; i++ )); do
  [ $[i%2] -eq 1 ] && let sum+=i
 done
echo sum=$sum

2.2 while loop

Usage:

while condition; do
  # loop body
 done

Special form for reading a file line by line:

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

Example: sum of all odd numbers less than 100.

#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"

2.3 until loop

Syntax is the opposite of while :

until condition; do
  # loop body
 done

Example: monitor a user and kill the process when the user logs in.

#监控xiaoming用户,登录就杀死
until pgrep -u xiaoming &> /dev/null; do
  sleep 0.5
 done
pkill -9 -u xiaoming

2.4 select loop (menu)

Creates an interactive menu:

select variable in list; do
  # commands
 done

Typical usage with case to handle the choice.

#生成菜单,并显示选中的价钱
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

Use continue [N] to skip to the next iteration of the N‑th outer loop, and break [N] to exit the N‑th outer loop.

#①求(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; let i++; }
done
echo sum=$sum

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

4. Signal Trapping with trap

Basic syntax:

trap 'command' SIGNAL   # execute command when SIGNAL is received
trap '' SIGNAL          # ignore SIGNAL
trap '-' SIGNAL          # restore default handling
trap -p                 # list current traps

Common signals: SIGHUP, SIGINT (Ctrl+C), SIGQUIT, SIGKILL, SIGTERM, SIGCONT, SIGSTOP.

Example: prevent Ctrl+C from terminating a loop.

#①打印0-9,ctrl+c不能终止
#!/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.

5. Miscellaneous Bash Snippets

Generating random characters:

#生成8个随机大小写字母或数字
cat /dev/urandom | tr -dc [:alnum:] | head -c 8

Generating random numbers:

echo $RANDOM               # raw random number
echo $[RANDOM%7]           # 0‑6
echo $[$[RANDOM%7]+31]     # 31‑37

Printing colored text:

echo -e "\033[31malong\033[0m"   # red text
echo -e "\033[1;31malong\033[0m" # bold red
echo -e "\033[41malong\033[0m"   # red background

5.1 9×9 Multiplication Table

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

5.2 Colored 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
    xing=$[2*$i-1]
    for j in `seq 1 $[ $num-$i ]`; do echo -ne " "; done
    for k in `seq 1 $xing`; do
      color=$[$[RANDOM%7]+31]
      echo -ne "\033[1;${color};5m*\033[0m"
    done
    echo
  done
fi

5.3 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] -eq 0 ]; then
    for j in {1..4}; do echo -ne "$red$yellow"; done; echo
  else
    for j in {1..4}; do echo -ne "$yellow$red"; done; echo
  fi
done

These snippets demonstrate practical Bash techniques for automation, user interaction, and visual output.

automationBashSignal Handlingshell scriptingloopsConditionals
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login 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.