Recap - Safe Cleanup
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 30 of 39.
Challenge
HardWrite 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.
- Start with
set -euo pipefail. - The list file is the only argument. With any other number of arguments, print
Usage: clean.sh FILEto stderr and exit with code 1. If the file does not exist, printNo such file: NAMEto stderr, with the argument in place of NAME, and exit with code 2. - Create a temp file with
mktemp ./tmp.XXXXXXand set atrapthat removes it when the script exits. - Read the list line by line. Skip blank lines. If a line has no
@, printBad line N: LINEto stderr, where N is its line number in the file (blank lines count), and exit with code 3. The original file must stay unchanged. - Write every other line in lowercase to the temp file.
- When all lines are read, move the temp file over the original and print
Cleaned NAME: N addresses. Notmp.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.orgThen 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
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground