Hands-on task
A robust script
Course finale: build a script you wouldn't be afraid to put in cron. Write an executable /usr/local/bin/snapshot that packs a directory into a tar.gz archive. The script is handy to write in the Editor tab above the terminal: the /usr/local/bin directory is open there next to /root.
Usage: snapshot [-w SECONDS] -o ARCHIVE DIR
-o ARCHIVE— required option: where to put the finished archive;-w SECONDS— optional pause before packing (default0), simulates long-running work;DIR— exactly one positional argument; the path may contain spaces.
Order of work: take a lock on the file /run/snapshot.lock with flock → create a temporary file /tmp/snapshot.XXXXXX with mktemp → wait for the -w pause → pack the directory into the temporary file → move it to ARCHIVE.
Requirements:
- Unknown option, option without a value, no
-o, no directory or an extra argument — a line containing the wordusageon stderr and exit code 2. - If another instance is already running — a message on stderr and exit code 3 right away: create nothing and don't touch the running instance's files.
- No temporary file is left behind after success, after an error, or after
SIGTERMorSIGINT. On a signal, the script exits with a non-zero code and no archive appears. - Strict mode: a failed command (including inside a pipeline) and a reference to an unset variable stop the script with a non-zero code — for example, for a nonexistent directory there must be no archive.
- getopts
- trap
- flock
- set -euo pipefail
- mktemp
- signals
- exit codes
- bash scripts