Table of Contents

BASH - Files - Read a file - Basic read

while read -r line; do
  printf '%s\n' "$line"
done < "$file"

NOTE: This reads each line of the file into the line variable.

  • line: is a variable name, chosen by you.
  • -r: Prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters).
    • Without this option, any unescaped backslashes in the input will be discarded.
    • You should almost always use the -r option with read.
  • < “$file”: The file to read.

Prevent removal of leading and trailing white-space characters

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

NOTE: Very similar to the basic read, but adding usage of IFS.

The IFS (internal field separator) is often set to support reads.

  • IFS= : By default, read modifies each line read, by removing all leading and trailing white-space characters (spaces and tabs, if present in IFS, which is the default).
    • To prevent this, the IFS variable is cleared.
  • line: is a variable name, chosen by you.
  • -r: Prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters).
    • Without this option, any unescaped backslashes in the input will be discarded.
    • You should almost always use the -r option with read.
  • < “$file”: The file to read.

Checking that returned line is not empty

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
  echo "Text read from file: $line"
done < "$1"

NOTE: The -n checks if the string is not null.

This is the opposite of -z, which checks if a string is null, i.e. it has zero length.