Own locks and publish completed output
Acquire a directory lock and preserve the previous report when collection fails.
A lock has an owner
Checking whether a lock exists and then creating it leaves a race between those two steps. mkdir combines the decision and creation: one contender creates the directory, while another fails. Only the process that successfully created the lock should remove it.
Install cleanup after acquiring ownership. If acquisition fails, return a clear busy status without deleting the existing lock or touching its contents. A stale lock needs deliberate operator recovery; a script cannot safely assume that an unfamiliar lock is abandoned merely because it is inconvenient.
Publish only completed work
The collector may produce some output and then fail. Redirect it into a temporary directory, inspect its status and move the completed file into place only on success. This preserves the previous report when the new collection is incomplete. Staging the file beside its destination also keeps the final move on the same filesystem in this exercise.
An EXIT trap centralises cleanup for both success and ordinary failure. It is not a guarantee against an uncatchable kill or power loss. A production tool also needs an explicit stale-lock recovery procedure and signal-aware child cleanup. Here the collector is a short-lived synchronous helper, and the exercise tests the ownership and publication boundaries without changing any host operating-system state.
if mkdir example.lock 2>/dev/null;then
printf 'this invocation owns the lock\n'
rmdir example.lock
fi
Put it into practice.
Acquire report.lock with mkdir. If it already exists, exit 3 with “Report busy” on stderr, leaving its owner.txt and report.txt intact. After acquisition, run bash tools/collect.sh into temporary output. On helper failure, exit 2 with “Collection failed”, retain report.txt and remove your lock/temp directory. On success, replace report.txt with exact helper output and remove your lock/temp directory. Use an EXIT trap installed only after acquiring the lock. Do not remove another invocation’s lock.
See an explained solution
if ! mkdir report.lock 2>/dev/null;then printf 'Report busy\n' >&2;exit 3;fi
work=
cleanup(){ [ -z "$work" ] || rm -rf "$work";rmdir report.lock; }
trap cleanup EXIT
work=$(mktemp -d .report.XXXXXX) || exit 2
if ! bash tools/collect.sh > "$work/report";then printf 'Collection failed\n' >&2;exit 2;fi
mv "$work/report" report.txt
The script separates acquiring ownership, collecting evidence and publishing a completed report. Its cleanup only removes resources it created, and failed collection cannot replace a previous useful report with partial bytes.