🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Reading Files

Reading a file line by line means handling one line at a time in a loop. A while loop with read does exactly that job.

Reading each line in turn

read fills the variable line with one file line at a time. The loop body prints each value in file order.

echo "milk" > list.txt
echo "bread" >> list.txt
while read line; do
  echo "$line"
done < list.txt

Numbering the lines

A counter starts at zero and grows by one on each pass. Printing it beside the line numbers the whole list.

echo "milk" > list.txt
echo "bread" >> list.txt
echo "eggs" >> list.txt
count=0
while read line; do
  count=$((count + 1))
  echo "$count: $line"
done < list.txt

Adding a label to each line

The loop body can build a new line from the one it read. Here each item gains the same Item label.

echo "milk" > list.txt
echo "bread" >> list.txt
while read line; do
  echo "Item: $line"
done < list.txt

Example

echo "wake up" > tasks.txt
echo "make tea" >> tasks.txt
echo "write code" >> tasks.txt
count=0
while IFS= read -r line; do
  count=$((count + 1))
  echo "Task $count: $line"
done < tasks.txt

Key points

  • The read command stores one line in the named variable.
  • The loop runs once for each line in the file.
  • The < symbol at the end feeds the file into the loop.
  • A counter variable can number the lines as they pass.
  • The form IFS= read -r line is the safe form of read.
  • The -r flag keeps backslashes in a line unchanged.

In this example, the loop uses the safe form IFS= read -r line. The counter numbers each task as the loop reads it from the file. The output lists all three tasks in order, each with its number.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In a while read loop, what does the < tasks.txt part do?