typestar

for loops in Bash

Three shapes: a word list, a C-style counter, a generated sequence.

# a for loop walks a list of words
for lang in bash zsh fish; do
    echo "shell: $lang"
done

# C-style counting lives in (( ))
for (( i = 0; i < 3; i++ )); do
    echo "count $i"
done

# brace expansion generates the list up front
for n in {1..5..2}; do
    echo "odd: $n"
done

How it works

  1. for lang in ... walks whatever words follow in.
  2. for (( ... )) counts like C when an index matters.
  3. {1..5..2} expands to the list before the loop starts.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
267
Tokens
54
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 36 seconds.

Type this snippet

Step 1 of 3 in Loops, step 7 of 26 in Language basics.

← Previous Next →