>_ IzzyLab

Hands-on task

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

A strict script without warnings

medium~8 min

Write /root/words.sh in strict mode set -euo pipefail that shellcheck won't find fault with. Without an argument the script prints a line starting with usage: to stderr and exits with code 64. With a file path it prints only the number of words in the file; the path may contain spaces. It's handy to write the script in the Editor tab above the terminal, and run shellcheck in the terminal.

What you'll practise:
  • set -euo pipefail
  • $#
  • exit codes
  • stderr
  • shellcheck

Topic breakdown

A robust script checks its input before it starts working. In strict mode that's especially important: because of set -u, touching a non-existent $1 crashes the script with an unclear error and code 1, so the number of arguments ($#) is checked first. The usage message goes to stderr (>&2) so it doesn't mix with useful output, and exit code 64 is the traditional EX_USAGE from sysexits.h, which lets the caller tell "called wrong" from "failed along the way". Paths go in double quotes — and shellcheck makes sure you don't forget.

What's checked

  1. strict mode and zero shellcheck warnings
  2. without an argument: usage on stderr and code 64
  3. counts words in a file with a space in its name

What it looks like