Control Flow Structures (if-else, case, for, while, until)

Control flow makes a script think: if-else and case choose between paths, while for, while, and until repeat work, so your backup script can decide what to do and loop over every file instead of running straight through once.

12 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Scripts that decide and repeat

A script that just runs its lines top to bottom, once, is useful but limited. Real scripts need to decide (if the backup folder does not exist, create it) and to repeat (copy every file in the list). That is control flow, and you have met the ideas before in Python and C; here you learn the shell's version.

There are two families: branching (if-else and case, choosing a path) and looping (for, while, until, repeating work). This lesson covers all five, with the shell's particular syntax and its distinctive closing keywords.

Theory

Branching: if-else and case

if runs a block only when a test succeeds, with optional elif (else-if) and else branches, and it closes with fi (if reversed):

if [ test ]; then ... elif [ test ]; then ... else ... fi

case compares one value against several patterns, cleaner than a long chain of elifs when you are matching a single variable. Each pattern ends with ;;, and the whole block closes with esac (case reversed). Use if for general true/false conditions, and case when you are checking one value against many specific possibilities.

Practical

if-elif-else and case (verified)

n=7
if [ $n -lt 5 ]; then
    echo "small"
elif [ $n -lt 10 ]; then
    echo "medium"          # n=7 -> prints medium
else
    echo "large"
fi

fruit=apple
case $fruit in
    apple)  echo "It is an apple" ;;   # this matches
    banana) echo "It is a banana" ;;
    *)      echo "Unknown" ;;          # * = anything else
esac

Theory

Looping: for, while, until

for repeats once for each item in a list, perfect for 'do this to every file':

for f in *.txt; do ... done

while repeats as long as a condition stays true: while [ test ]; do ... done. until is its mirror image: it repeats until a condition becomes true (that is, while the condition is still false). All three loops close with done.

So while [ $i -le 3 ] keeps going while i is 3 or less, and until [ $i -gt 3 ] keeps going until i exceeds 3, both, counting from 1, print 1, 2, 3. Choose the one whose condition reads most naturally.

Practical

for, while, and until (verified)

# for: iterate over a list
for f in *.txt; do
    echo "file: $f"
done

# while: repeat WHILE the condition is true
i=1
while [ $i -le 3 ]; do
    echo "while $i"        # prints while 1, while 2, while 3
    i=$((i+1))
done

# until: repeat UNTIL the condition becomes true
i=1
until [ $i -gt 3 ]; do
    echo "until $i"        # also prints 1, 2, 3
    i=$((i+1))
done

Formula

Mind the closing keywords

The shell closes each block with a specific word, and mixing them up is a common error:

if closes with fi, case closes with esac (both are the keyword spelled backwards), and every loop, for, while, until, closes with done.

Also remember the ;; after each case pattern, and that the test [ ... ] needs spaces inside the brackets. These small syntax details are exactly what trips up shell beginners, so type them deliberately.

Quiz

What does this loop print? i=1; while [ $i -le 3 ]; do echo $i; i=$((i+1)); done

  1. 1 2 3 4, counting to 4
  2. 1 2 3, one number per line
  3. Nothing, because the condition is false at the start
  4. An infinite loop
Show the answer

1 2 3, one number per line

The loop runs while i is less than or equal to 3. Starting at i=1: it prints 1 (then i becomes 2), prints 2 (i becomes 3), prints 3 (i becomes 4), and now 4 is not <= 3, so it stops, giving 1, 2, 3, each on its own line. Option A is off by one: when i reaches 4 the condition [ 4 -le 3 ] is false, so 4 is never printed. Option C is wrong: at the start i=1, and [ 1 -le 3 ] is true, so the loop does run. Option D is wrong: because i increases each pass (i=$((i+1))), the condition eventually fails and the loop ends, it is not infinite. Trace the counter carefully: -le 3 stops after 3.

Think first

while or until: how do you choose?

while and until are mirror images. When does each read more naturally? Then tap.

Show the answer

Choose whichever makes the CONDITION read as a plain-English intention, because they are logical opposites. while repeats as long as its condition is TRUE, so it fits when you think 'keep going WHILE something holds': while there are still files to process, while the user has not typed quit, while the counter is within range. until repeats as long as its condition is FALSE, stopping once it becomes true, so it fits when you think 'keep going UNTIL something happens': until the server responds, until the download completes, until the counter exceeds the limit. The two can always be rewritten as each other by flipping the test, while [ $i -le 3 ] and until [ $i -gt 3 ] loop over exactly the same values 1, 2, 3, so the choice is about READABILITY, not capability. Pick the phrasing that matches how you naturally describe the stopping point, and your script becomes easier to read and less error-prone. If you catch yourself writing a while with a negated, awkward condition, an until may express it more clearly, and vice versa. Same loop, clearer intent.

Summary

Key takeaways

  • Control flow lets a script decide (branching) and repeat (looping), just like Python and C but with shell syntax.
  • if-then-elif-else-fi chooses a path from tests; case matches one value against patterns and closes with esac.
  • for iterates over a list (for f in *.txt); ideal for doing something to every file.
  • while repeats as long as its condition is true; until repeats until its condition becomes true (the mirror image).
  • Closing keywords matter: if closes with fi, case with esac, and all loops with done.
  • while [ $i -le 3 ] counting from 1 prints 1, 2, 3, and stops when i reaches 4.
  • Memory hook: if/case decide, for/while/until repeat; fi, esac, done to close.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Shell Scripting in Linux

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Control Flow Structures (if-else, case, for, while, until) · Linux Operating System (LOS) (Minor-04) · Gri-Learn