Menu
CoddyTech

Recap - Safe Cleanup

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 30 of 39.

challenge icon

Challenge

Hard

Write clean.sh, a strict script that cleans an email list in place. It builds the new list in a temp file and replaces the original only when every line is valid.

  1. Start with set -euo pipefail.
  2. The list file is the only argument. With any other number of arguments, print Usage: clean.sh FILE to stderr and exit with code 1. If the file does not exist, print No such file: NAME to stderr, with the argument in place of NAME, and exit with code 2.
  3. Create a temp file with mktemp ./tmp.XXXXXX and set a trap that removes it when the script exits.
  4. Read the list line by line. Skip blank lines. If a line has no @, print Bad line N: LINE to stderr, where N is its line number in the file (blank lines count), and exit with code 3. The original file must stay unchanged.
  5. Write every other line in lowercase to the temp file.
  6. When all lines are read, move the temp file over the original and print Cleaned NAME: N addresses. No tmp. file may be left behind in any case.

Try it: run bash clean.sh contacts.txt, then cat contacts.txt. They print:

Cleaned contacts.txt: 3 addresses
ana@shop.com
ben@shop.com
cara@mail.org

Then run bash clean.sh broken.txt. It prints Bad line 2: Eli at home, exits with code 3 and leaves broken.txt as it was.

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground