Master Bash Conditionals, Loops, and Signal Traps with Real‑World Examples
This article provides a comprehensive guide to Bash scripting, covering if/elif/else conditionals, case statements, four types of loops (for, while, until, select), signal trapping with trap, useful one‑liners for randomness and colored output, and several fun scripts such as a multiplication table, colored triangle, and chessboard.
1. Conditional Selection and Judgment (if)
The if statement evaluates conditions sequentially; the first true condition executes its branch and the whole if block ends. Syntax example:
if condition1; then
# commands for true branch
elif condition2; then
# commands for second true branch
else
# commands when all conditions are false
fiExample – age validation:
# 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"
fiAnalysis: The script first checks for non‑numeric input, then validates the range, and finally distinguishes adults from minors.
Example – score validation follows the same pattern, checking for non‑numeric input, out‑of‑range values, and grading thresholds.
2. Case Statement
The case construct matches a variable against patterns using glob‑style wildcards.
case $name in
PATTERN1) cmd ;;
PATTERN2) cmd ;;
*) cmd ;;
esacExample – yes/no detection (accepts various capitalizations):
# 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 ;;
esac3. Four Loop Types
3.1 for Loop
Two forms are supported:
# List iteration
for var in list; do
# loop body
done
# C‑style arithmetic iteration
for (( init; condition; increment )); do
# loop body
doneExample – sum of numbers 1 to n:
# Compute sum 1+2+...+n
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
fi3.2 while Loop
Executes as long as the condition is true; the condition is evaluated before each iteration.
while condition; do
# loop body
doneExample – sum of odd numbers up to 100:
# Sum of 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"3.3 until Loop
The until loop runs until its condition becomes true (the opposite of while).
until condition; do
# loop body
doneExample – 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 xiaoming3.4 select Loop (Menu)
The select construct creates an interactive numbered menu.
PS3="Please choose the menu: "
select menu in option1 option2 quit; do
case $REPLY in
1|2) echo "you chose $menu" ;;
3) break ;;
*) echo "invalid option" ;;
esac
done4. Signal Trapping with trap
The trap command associates a command with a signal, allowing custom handling.
# Example – ignore Ctrl+C (SIGINT) for the first 3 iterations
#!/bin/bash
trap '' SIGINT # ignore
for i in {0..2}; do
sleep 1
echo $i
done
trap - SIGINT # restore default handling
for i in {3..9}; do
sleep 1
echo $i
done5. Handy Bash One‑Liners
Generate 8 random alphanumeric characters: cat /dev/urandom | tr -dc '[:alnum:]' | head -c 8 Generate a random number: echo $RANDOM (e.g., echo $((RANDOM%7+31)) for 31‑37)
Print colored text using ANSI escape codes, e.g.,
echo -e "\033[31malong\033[0m"6. Fun Scripts
6.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 -ne "${a}x${b}=${c}\t\c"
done
echo
done6.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
stars=$((2*i-1))
for ((j=1; j<=num-i; j++)); do echo -n " "; done
for ((k=1; k<=stars; k++)); do
color=$((RANDOM%7+31))
echo -ne "\033[1;${color};5m*\033[0m"
done
echo
done
fi6.3 ASCII Chessboard
#!/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
doneSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
