This session introduces the essential building blocks for creating dynamic and decision-making shell scripts: conditional logic and exit code handling.
Learning Objectives
- Implement conditional logic using
if,elif, andelsestructures. - Understand and utilize various test operators for file, string, and numeric comparisons.
- Master the use of the
casestatement for multi-way branching. - Learn to check and utilize command exit codes (
$?) for flow control.
Topics Covered
1. Conditional Execution with if Statements
- Structure: The standard
if ... then ... elif ... else ... fiblock. - The Test Command:
[ ... ]: Standard POSIX test. Needs quoting for variables.[[ ... ]]: Modern Bash test. Handles empty variables better and supports pattern matching.- Pattern Matching (Advanced):
bash
if [[ "$filename" == *.jpg ]]; then
echo "It is a JPEG image."
fi
- Regex Matching (Advanced):
bash
if [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$ ]]; then
echo "Valid email format."
fi
2. Comparison Operators
- File Tests: Checking for existence, type (file/directory), and permissions (
-f,-d,-r,-x). - String Comparisons: Equality (
=), inequality (!=), and emptiness (-z,-n). - Numeric Comparisons: Using
-eq,-ne,-gt,-lt(must use these for numbers, not standard operators like>,<).
3. The case Statement
- Multi-way Branching: Much cleaner than multiple
ifstatements when checking one variable. - Pattern Matching & Fall-through:
bash
case "$extension" in
jpg|jpeg|png) echo "Image file" ;;
mp3|wav|flac) echo "Audio file" ;;
*) echo "Unknown format" ;;
esac
4. Exit Statuses and Short-Circuiting
- Boolean Logic:
cmd1 && cmd2: Runcmd2only ifcmd1succeeded.cmd1 || cmd2: Runcmd2only ifcmd1failed.- The
!operator: Negating a condition.
bash
if ! grep -q "secret" config.txt; then
echo "Security check passed."
fi
Lab/Assessment Focus
Goal: Create a robust file_checker.sh.
- Validation: Use
[[ -z "$1" ]]to check if an argument was provided. - Logic: Check if the path exists (
-e) and if it's a directory (-d). - Permissions: Check if it's readable (
-r) and writable (-w). - Case Statement: Use a
casestatement to handle different file extensions if the user passes a file instead of a directory. - Output: Use
&&to print success only if the previous checks passed.
Advanced Topic References
- Bash Conditional Expressions: Official Bash documentation on tests.
- When to use
[ ]vs[[ ]]in Bash: A comparison of test syntaxes. - Exit Codes Explained: Understanding process termination values.