>_ IzzyLab

Hands-on task

This task is step 6 of the course “Clean scripts: shellcheck”

Read a file with while read

medium~7 min

The script /root/print.sh reads /root/items.txt with a for line in $(cat ...) construct and tears lines containing spaces apart. Rewrite the reading so that shellcheck is clean and the line hello world stays intact. Open the script in the Editor tab above the terminal, and run shellcheck in the terminal.

What you'll practise:
  • shellcheck
  • while read
  • SC2013
  • IFS
  • line-by-line reading

Topic breakdown

The idiom for reading a file line by line in bash is while IFS= read -r line; do … done < file. read takes one line at a time from the redirected input; IFS= in front of it disables stripping of leading/trailing whitespace, and -r prevents backslash interpretation. The anti-pattern for x in $(cat file) substitutes the whole text and splits it on IFS (spaces AND newlines), so lines with spaces fall apart and glob characters get expanded; shellcheck warns about this with rule SC2013.

What's checked

  1. shellcheck reports nothing
  2. the line with a space is intact

What it looks like