>_ IzzyLab

Hands-on task

This task is step 30 of the course “Bash scripts: from a loop to a robust script”

A size-counting script: zero warnings

medium~7 min

The script /root/dirsize.sh appends a line <directory>: <N> bytes to /var/reports/summary.log for the directory given as the first argument. It breaks on a directory with a space in its name (/srv/my data), and shellcheck finds several issues in it. Fix them all so that shellcheck is silent and the script works on such paths too. Open the script in the Editor tab above the terminal.

What you'll practise:
  • shellcheck
  • quoting
  • $( )
  • cd || exit
  • spaces in paths

Topic breakdown

shellcheck warnings are independent, and one script usually has several — it's worth going through them as a list, by the SCxxxx code. The most common one is a variable substitution without quotes: a path with a space becomes two arguments after it, and the command works on the wrong file. Outdated backticks are replaced with $( … ), which reads more easily and nests without escaping. And an unchecked cd is dangerous: if the directory is missing, the script carries on where it was and writes files to the wrong place. A clean shellcheck output isn't a goal in itself, but a sign that these edge cases are covered.

What's checked

  1. shellcheck has no warnings
  2. the script works with a space in the path

What it looks like