Idempotent setkv Capstone: Make a Config Writer Safe and Repeatable (Graded by Running It)
ExpertShell Scripting40-60 minThe tool s9setkv FILE KEY VALUE must ensure the line KEY=VALUE appears in FILE exactly once — replacing an existing KEY= line or appending a new one — and running it again with the same arguments must change nothing. The starter version is fragile. Harden it; you are graded by the grader running your script against adversarial inputs. See /root/brief.txt for the path and contract.
Make it satisfy all six properties:
1. Validate args — wrong argument count or missing FILE → non-zero exit, no change.
2. Append when absent — a new key adds exactly one KEY=VALUE line.
3. Update when present — an existing key is replaced; no duplicate KEY= lines.
4. Idempotent — running twice leaves exactly one KEY= line.
5. Preserve others — unrelated lines stay intact.
6. Literal value — a value with /, &, or spaces (e.g. /etc/foo bar) is stored exactly (beware sed replacement strings; a literal printf write is safer).
Keep the same path and keep it executable.
- Write an idempotent config-line setter that never duplicates keys
- Handle both the append (new key) and update (existing key) cases correctly
- Store values literally, avoiding sed replacement-string injection
- Validate arguments and fail safely without corrupting the file
- Understand why 'set it once' scripts must be safe to run repeatedly
Hands-on lab: you work on a real Linux box in your browser, graded on the machine's actual state.
