Bird
Raised Fist0
Bash Scriptingscripting~10 mins

for loop (list-based) in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - for loop (list-based)
Start
↓
Define list
↓
Pick first item
↓
Execute loop body
↓
More items?
No→End loop
Yes↓
Pick next item
↩Back to Execute loop body
The loop picks each item from the list one by one and runs the commands inside the loop for each item.
Execution Sample
Bash Scripting
items=(apple banana cherry)
for item in "${items[@]}"
do
  echo "$item"
done
This script loops over a list of fruits and prints each fruit on its own line.
Execution Table
Iterationitem valueActionOutput
1applePrint itemapple
2bananaPrint itembanana
3cherryPrint itemcherry
--No more items, exit loop-
💡 All items processed, loop ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
itemundefinedapplebananacherrycherry
Key Moments - 3 Insights
Why does the loop stop after the last item?
The loop checks if there are more items in the list. When no items remain (see last row in execution_table), it stops.
What if the list is empty?
If the list is empty, the loop body never runs because there are no items to pick, so no output is produced.
Why do we use "${items[@]}" instead of just "$items"?
Using "${items[@]}" expands each list element separately, so the loop gets each item individually. Using "$items" would treat the whole list as one string.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'item' during iteration 2?
Abanana
Bapple
Ccherry
Dundefined
💡 Hint
Check the 'item value' column in the second row of the execution_table.
At which iteration does the loop stop running?
AAfter iteration 1
BAfter iteration 3
CAfter iteration 2
DIt never stops
💡 Hint
Look at the exit_note and the last row in execution_table.
If the list was empty, what would the output be?
Aapple banana cherry
BError message
CNo output
DLoop runs once with empty item
💡 Hint
Refer to the key_moments explanation about empty lists.
Concept Snapshot
for item in "${items[@]}"; do
  commands using $item
 done

- Loops over each item in the list
- Runs commands once per item
- Stops after last item
- Use "${items[@]}" to get each element separately
Full Transcript
This visual shows how a bash for loop works with a list. The loop starts by defining a list of items. Then it picks the first item and runs the commands inside the loop body using that item. It repeats this for each item in the list. When there are no more items, the loop stops. The variable 'item' changes each iteration to the current list element. If the list is empty, the loop does not run at all. Using "${items[@]}" ensures each item is handled separately. This is a simple way to repeat actions for each element in a list in bash scripting.

Practice

(1/5)
1. What does the following Bash code do?
for item in apple banana cherry; do echo $item; done
easy
A. Prints each fruit name on a new line
B. Prints all fruit names on the same line
C. Creates a list of fruits without printing
D. Causes a syntax error

Solution

  1. Step 1: Understand the for loop structure

    The loop goes through each word in the list: apple, banana, cherry.
  2. Step 2: Check the command inside the loop

    It prints each item using echo, so each fruit name appears on its own line.
  3. Final Answer:

    Prints each fruit name on a new line -> Option A
  4. Quick Check:

    Loop prints each item line by line = C [OK]
Hint: For loops print each list item one by one [OK]
Common Mistakes:
  • Thinking echo prints all items on one line
  • Confusing list iteration with variable assignment
  • Missing the do/done keywords
2. Which of these is the correct syntax for a Bash for loop over a list of words?
easy
A. loop item in apple banana cherry: echo $item
B. for (item in apple banana cherry) { echo $item }
C. for item in apple banana cherry; do echo $item; done
D. foreach item in apple banana cherry; echo $item; end

Solution

  1. Step 1: Identify valid Bash for loop syntax

    Bash uses: for variable in list; do commands; done
  2. Step 2: Compare options

    Only for item in apple banana cherry; do echo $item; done matches Bash syntax exactly; others use syntax from other languages or invalid forms.
  3. Final Answer:

    for item in apple banana cherry; do echo $item; done -> Option C
  4. Quick Check:

    Bash for loop syntax = D [OK]
Hint: Bash loops use 'for var in list; do ...; done' [OK]
Common Mistakes:
  • Using parentheses or braces like other languages
  • Using foreach or loop keywords not in Bash
  • Omitting do or done keywords
3. What is the output of this script?
for word in one two three; do echo "$word"; done
medium
A. one two three (each on its own line)
B. one\ntwo\nthree
C. one two three
D. one two three

Solution

  1. Step 1: Understand the loop iteration

    The loop runs three times, each time echoing one word: one, two, three.
  2. Step 2: Understand echo output with quotes

    Quotes preserve spaces but echo prints each word on a new line by default.
  3. Final Answer:

    one two three (each on its own line) -> Option A
  4. Quick Check:

    Echo prints each item on separate lines = A [OK]
Hint: Echo prints each loop item on its own line by default [OK]
Common Mistakes:
  • Thinking echo prints all items on one line
  • Confusing literal \n with newline
  • Ignoring quotes effect on output
4. Find the error in this Bash script:
for item apple banana cherry; do echo $item; done
medium
A. Missing semicolon after 'banana'
B. Variable name 'item' is invalid
C. Incorrect use of quotes around list items
D. Missing 'in' keyword after 'for item'

Solution

  1. Step 1: Check for loop syntax

    Bash requires 'for variable in list; do ...; done'. The 'in' keyword is missing here.
  2. Step 2: Identify the error cause

    Without 'in', Bash cannot parse the list, causing a syntax error.
  3. Final Answer:

    Missing 'in' keyword after 'for item' -> Option D
  4. Quick Check:

    For loop needs 'in' keyword = B [OK]
Hint: Always include 'in' after variable in for loops [OK]
Common Mistakes:
  • Forgetting the 'in' keyword
  • Adding unnecessary semicolons inside list
  • Misnaming variables with invalid characters
5. You want to print only the fruits that start with the letter 'b' from this list:
fruits="apple banana cherry blueberry"
for fruit in $fruits; do
  # Fill condition here
  echo "$fruit"
done

Which condition inside the loop correctly filters fruits starting with 'b'?
hard
A. if [ $fruit = 'b' ]; then
B. if [[ $fruit == b* ]]; then
C. if [[ $fruit =~ b* ]]; then
D. if [ $fruit == 'b*' ]; then

Solution

  1. Step 1: Understand string pattern matching in Bash

    Double brackets [[ ]] support pattern matching with == and wildcards like '*'.
  2. Step 2: Check each condition

    A uses [[ $fruit == b* ]] which matches strings starting with 'b'. B uses single brackets for exact 'b' match. C uses [[ $fruit =~ b* ]]; b* regex matches zero or more 'b's (including none), so every string. D uses single brackets which don't support patterns or ==.
  3. Final Answer:

    if [[ $fruit == b* ]]; then -> Option B
  4. Quick Check:

    Use [[ var == pattern* ]] for prefix match = A [OK]
Hint: Use [[ var == prefix* ]] to match string start in Bash [OK]
Common Mistakes:
  • Using single brackets with wildcard patterns
  • Confusing regex =~ with == operator
  • Comparing to exact string 'b' instead of prefix
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard