typestar

while read in Bash

The line-by-line loop that processes streams.

# while read consumes input line by line; IFS= keeps leading spaces
printf 'alpha\n  beta\ngamma\n' | while IFS= read -r line; do
    echo "got: [$line]"
done

# a counter loop with a condition
n=1
while (( n < 30 )); do
    n=$(( n * 3 ))
done
echo "stopped at $n"

How it works

  1. IFS= read -r reads one raw line, spaces and all.
  2. The pipe feeds the loop; each iteration gets one line.
  3. (( )) conditions drive counter loops the same way.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
257
Tokens
46
Three-star pace
80 tpm

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

Type this snippet

Step 2 of 3 in Loops, step 8 of 26 in Language basics.

← Previous Next →