← All Exercises
Update a Config Value with sed In Place
intermediatebash
Background
Deployment scripts often patch a single setting. In-place edits need escaping, validation, and backups because sed treats several characters specially.
Problem
Write a script that sets a key in a config file to a new value. The key must already exist, the value must be escaped for sed, and a backup must be created before reporting the result.
Input
A writable config file, an existing key matching [A-Za-z_][A-Za-z0-9_.-]*, and an arbitrary replacement value passed as one shell argument.
Output
The file keeps its other lines, the matching key is replaced, <file>.bak holds the previous content, and stdout reports updated or unchanged.
Sample tests
Sample 1
Input: app.ini containing '# app.ini', 'retries=3', 'timeout = 30'; set timeout to 60
Expected: updated: timeout -> 60 (backup: app.ini.bak)
Sample 2
Input: run the same command again on the updated file
Expected: unchanged: timeout already 60
Your solution
Learning objective
Escape sed replacement characters, anchor and validate keys, and use a backup for idempotent configuration edits.