Master Bash: Essential Conditionals, Loops, and Signal Tricks for Linux Scripts
This guide walks you through Bash scripting fundamentals, covering conditional statements (if, case), four loop types (for, while, until, select), loop control commands (continue, break, shift), signal trapping with trap, plus practical examples and handy one‑liners for automation.
1. Conditional Selection and Judgment (if, case)
(1) if statement
Syntax: if [condition]; then... elif [condition]; then... else... fi The first true condition executes its branch and the whole if block ends.
Example – Age validation
Prompt for age, reject non‑numeric input, then ensure the value is between 18 and 150.
Example – Score validation
Prompt for a score, reject non‑numeric input, then check ranges >100, >85, >60.
(2) case statement
Syntax:
case $variable in pattern1) commands ;; pattern2) commands ;; *) commands ;; esacSupports glob patterns: *, ?, [...], a|b.
Example – Yes/No prompt
Accepts various capitalizations of yes (Y/y/yes) and no (N/n/no).
2. Four Loop Types (for, while, until, select)
(1) for loop
Syntax: for var in list; do... done Or arithmetic form: for ((exp1; exp2; exp3)); do...
doneExample – Sum of 1+2+…+n using arithmetic for loop.
Example – Sum of 1+2+…+100 using list expansion.
(2) while loop
Syntax: while [condition]; do... done Condition is evaluated before each iteration; loop stops when condition becomes false.
Special usage – reading a file line by line:
while read line; do
# process $line
done < /path/to/fileExample – Sum of odd numbers below 100.
(3) until loop
Syntax: until [condition]; do... done Runs until the condition becomes true (inverse of while).
Example – Monitor user "xiaoming" and kill the process when they log in.
(4) select loop (menu)
Syntax: select var in list; do... done Creates a numbered menu; user input is stored in REPLY. Use break to exit.
Example – Generate a menu and display the selected price.
3. Loop Control Statements
continue [N] – skip the rest of the current loop iteration and continue with the next one (N specifies the loop level).
break [N] – exit the current loop (N specifies the loop level).
Example code snippet:
while CONDITION1; do
CMD1
if CONDITION2; then
continue # or break
fi
CMD2
done4. shift Command
Purpose: Left‑shift the positional parameters, discarding the leftmost one.
Example – Create multiple users from arguments:
5. Return Values
truealways returns success; : (null command) does nothing and returns success; false always returns failure.
Creating an infinite loop:
while true; do
# commands
done6. Parallel Execution in Loops
Run loop bodies in background and wait for all to finish:
for name in list; do
{ commands; } &
done
waitExample – Scan a subnet for active IPs in parallel.
7. Signal Trapping (trap)
Syntax: trap 'command' SIGNAL Common signals: SIGHUP (reload config), SIGINT (Ctrl+C), SIGQUIT (Ctrl+\), SIGKILL (cannot be trapped), SIGTERM (default termination), SIGCONT (continue), SIGSTOP (background suspend).
Example – Prevent Ctrl+C from terminating a counting loop:
8. Miscellaneous Bash Tips
Generate random alphanumeric string: cat /dev/urandom | tr -dc '[:alnum:]' | head -c 8 Generate random number: echo $RANDOM (range 0‑32767). Use modulo for custom ranges.
Print colored text: echo -e "\033[31mred\033[0m" (red), \033[1;31m (bold red), \033[41m (red background), \033[31;5m (blinking red).
9. Sample Mini‑Scripts
9×9 multiplication table, colorful isosceles triangle, chessboard pattern – each illustrated with images.
This tutorial equips readers with the essential Bash constructs to automate tasks, build interactive menus, handle signals, and write efficient scripts for Linux environments.
Signed-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.
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.
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.
