Shell Scripting & Idempotency
The discipline of writing robust, re-runnable system administration scripts that converge to a desired state.
Knowledge
- •
The Doctrine of Idempotency
code* **Definition:** An idempotent script produces the same result whether run once or a thousand times. * **State Checking:** Never assume the state. Always check if a user exists, a file is present, or a service is running *before* attempting to change it. * **Convergence:** The goal is not just to execute commands, but to bring the system into compliance with a desired configuration.
- •
Safe Mutation Patterns
code* **Files:** Use `install` for setting permissions and ownership atomically. Use `grep` before `echo >>` to avoid duplicate config lines. * **Directories:** Always use `mkdir -p`. * **Users/Groups:** Check `/etc/passwd` or `getent` before invoking `useradd`/`adduser`. * **Services:** Use `service <name> status` or `rcctl check` before restart/reload actions.
- •
Robustness & Safety
code* **Error Handling:** Scripts should generally fail fast (`set -e`) or handle errors explicitly. * **Variables:** Always quote variables (`"$VAR"`) to handle whitespace correctly. * **Paths:** Use absolute paths for critical system binaries or set a strict `PATH` at the top of the script.
Abilities
- •Writing conditional logic (
if ! grep -q ...) to ensure configuration changes are not duplicated. - •Creating 'Check-then-Act' blocks for system resources (Users, Groups, Packages).
- •Utilizing
mktempfor safe temporary file handling. - •Ensuring scripts are non-interactive (e.g.,
apt-get -y,pkg install -y) for automation compatibility.