Skip to main content
So far our scripts have been linear lists of commands. Conditionals and loops make shell scripts smarter and far more useful for real-world automation.
  • Conditionals let a script choose between actions (do X if a condition is true, otherwise do Y).
  • Loops let a script repeat actions over collections of items without duplicating commands.
A dark presentation slide titled "Conditionals and Loops" with a neon-blue flowchart decision diamond on the right, showing a checkmark and an X for the two branches.
Below are compact, practical examples showing a for loop and an if conditional. These illustrate how you can iterate over items and branch logic for each item.
Key points from the examples:
  • The for loop repeats the commands in its body for each value in the list (user1, user2, user3), avoiding repeated manual commands.
  • The if statement evaluates the test expression and executes the appropriate branch.
  • Always quote variables (for example, "$user") to avoid word-splitting and unexpected glob expansion.
Always include spaces around the brackets and operators in conditional expressions (for example: if [[ $a -eq 1 ]]; then), and quote variables when you expect string values (for example: echo "$var").
When writing conditionals in Bash, you’ll use a small set of comparison operators for numeric and string comparisons. The following table summarizes the most common numeric operators used inside [ ] or [[ ]]:
A dark-themed slide titled "Conditional Operators." It lists comparison operators and their meanings (e.g., -gt greater than, -lt less than, -eq equal to, == for string equality, != not the same).
String comparisons and pattern matching
  • In [[ ... ]] you may use == (or =) for equality and != for inequality. [[ supports glob-style pattern matching on the right-hand side of ==:
  • In POSIX [...] form, prefer = for equality to stay portable (== is supported by many shells but not universally portable).
Arithmetic comparisons with (( … ))
  • The arithmetic evaluation form (( ... )) lets you use familiar C-like operators: ==, !=, <, >, <=, >=. It treats variables as arithmetic values and is convenient for numeric logic:
Best practices and common pitfalls
  • Quote variables when expanding strings: "$var".
  • Always put spaces around brackets and operators: if [[ $x -eq 1 ]]; then.
  • Prefer [[ ... ]] in Bash for safer and more flexible tests (pattern matches, no pathname expansion, logical operators within).
  • Use (( ... )) for arithmetic: clearer and more concise for numeric comparisons.
Be careful with portability: [[ ... ]] and (( ... )) are Bash extensions. Scripts intended for POSIX sh should use [...] and expr/awk or POSIX-compliant arithmetic expansion.
Combining loops and conditionals
  • The real power of shell scripting comes from combining loops with conditionals to process lists of files, users, or other resources and make decisions per-item:
Further reading and references

Watch Video