>_ IzzyLab

Hands-on task

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

Make cd safe

medium~5 min

The script /root/clean.sh changes into a directory and deletes temporary files there. shellcheck warns that cd without a check is dangerous: if the change fails, the script will keep running in the wrong place. Fix it so the linter stays silent while the behavior remains the same. Open the script in the Editor tab above the terminal, and run shellcheck in the terminal.

What you'll practise:
  • shellcheck
  • SC2164
  • cd
  • error handling
  • ||

Topic breakdown

Warning SC2164 is about cd possibly failing (no directory, no permissions) while the script doesn't notice and keeps running in an unexpected place — especially dangerous if file deletion follows. The reliable-shell idiom: a critical command must abort the script on failure. To do this you append an emergency action — exiting the script — via the || operator (which fires only on a non-zero exit code).

What's checked

  1. shellcheck without warnings
  2. the script stops when cd fails
  3. old.log is deleted in the normal case

What it looks like