SkillByAIOpen interactive version →

Lesson 26 / 31

Loops in Bash

Repeat tasks with for and while loops in Bash, iterating over files, lists and counters.

for loop

Iterate over a list of values or files.

for f in *.txt; do
    echo "Found: $f"
done

Output:

Found: notes.txt
Found: todo.txt

while loop

Runs as long as its condition stays true.

count=1
while [ $count -le 3 ]; do
    echo "count: $count"
    count=$((count + 1))
done

Output:

count: 1
count: 2
count: 3

Quick check: In `[ $count -le 3 ]`, what does `-le` mean?

  • less than
  • not equal
  • greater than
  • less than or equal to
Answer

less than or equal to — `-le` is bash's numeric "less than or equal to" test operator.