Read a File Line by Line in Bash

Loop over lines without losing whitespace or interpreting escapes.

macOSbashshellscriptingLow risk
Use while IFS= read -r line; do ...; done < file to iterate line by line.

01Command

Command
$ while IFS= read -r line; do printf "%s\n" "$line"; done < file.txt

02What it does

The combination IFS= read -r preserves leading and trailing whitespace and treats backslashes literally, which is exactly what log or config processing needs. Feeding the file with < (rather than a pipe) keeps the loop in the current shell so variables survive.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: Piping into the loop instead of redirecting runs it in a subshell and loses variable assignments.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer