Menu
CoddyTech

Reading Files Line By Line

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 20 of 39.

A while read loop reads a file one line at a time. read -r line puts the next line in line, and the loop ends when the file has no lines left. done < file sends the file into the loop. IFS= keeps the spaces at the start and end of each line, and -r keeps backslashes as they are.

n=1
while IFS= read -r line; do
  echo "$n: $line"
  ((n++))
done < todo.txt

For a CSV, write IFS=, and give read one variable per column: it splits each line at the commas. To skip a header, read it once before the loop. The braces group both commands so they read from the same file:

{
  read -r header
  while IFS=, read -r city temp; do
    echo "$city is at $temp degrees"
  done
} < temps.csv

When temps.csv holds city,temp, Oslo,4 and Cairo,31, this prints Oslo is at 4 degrees and Cairo is at 31 degrees. The last variable takes the rest of the line, commas included.

challenge icon

Challenge

Medium

Write a script that reads a stock CSV and flags items that are running low.

  1. Open stock.sh. Its first argument is a CSV file whose first line is the header item,qty.
  2. Skip the header, then read each row into item and qty.
  3. For each row print ITEM: QTY, and add (low) at the end of the line when QTY is under 5.
  4. Save the file.

Try it: run bash stock.sh stock.csv. It prints:

apples: 12
pears: 3 (low)
plums: 40
figs: 0 (low)

Then run bash stock.sh deli.csv, where one item name has a space:

blue cheese: 2 (low)
ham: 7

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground