📝

Bash Conditional Statements

Jul 17, 2025

Overview

This lecture explains how to use if, elif, and else statements in Bash scripting, with syntax, condition types, and practical examples.

Basics of Bash If Statements

  • Bash if statements execute code blocks based on specified conditions.
  • Basic syntax: if [ condition ]; then ... fi
  • If the condition is true, commands within the block run; otherwise, they're skipped.

Specifying Conditions in Bash

  • Single Parentheses ( ): Runs commands in a subprocess and checks exit status for true (0) or false (non-zero).
  • Double Parentheses (( )): Performs arithmetic evaluation; true if result ≠ 0, false if result = 0.
  • Single Brackets [ ]: Used for test expressions (e.g., string or variable checks).
  • Double Brackets [[ ]]: Enhanced test expressions; allows pattern matching and logical operators (&& for AND, || for OR).

Using Logical Operators and Patterns

  • Double brackets allow complex expressions with regex patterns and logical operators.
  • Example: [[ "$str" =~ [abc]+[123]+-* ]] checks if a string matches a specific pattern.
  • Logical AND (&&) requires both conditions to be true; OR (||) requires at least one to be true.*

Bash If Else Statements

  • else block defines actions when the if condition is false.
  • Syntax: if [ condition ]; then statements else statements fi
  • Example: Validate username input and give feedback based on match.

Bash If Elif Else Statements

  • elif allows multiple sequential condition checks.
  • Syntax: if [ condition ]; then statements elif [ condition ]; then statements else statements fi
  • Used to check several possible values or situations.

Nested If Else Statements

  • Nested if blocks allow multiple, layered checks for complex logic.
  • Example: Check both username and password for authentication.
  • Only executes the inner block if the outer condition is also true.

Key Terms & Definitions

  • if statement — Executes code if a specified condition is true.
  • elif statement — Tests an additional condition if the prior one was false.
  • else statement — Specifies code to run if all previous conditions are false.
  • [ ] — Tests expressions (strings, numbers, files).
  • [[ ]] — Advanced test operator for pattern matching and logical expressions.
  • (( )) — Arithmetic evaluation; true if result is nonzero.
  • ( ) — Runs commands in a subprocess for status checking.

Action Items / Next Steps

  • Practice writing Bash scripts using if, elif, and else with different condition types.
  • Experiment with pattern matching and logical operators using double brackets.
  • Review nested if structures and avoid unnecessary complexity.