Skip to content

Instantly share code, notes, and snippets.

@bencmbrook
Last active February 17, 2026 20:01
Show Gist options
  • Select an option

  • Save bencmbrook/43ba83c47621e5ee6c040e8b6bf3cf7d to your computer and use it in GitHub Desktop.

Select an option

Save bencmbrook/43ba83c47621e5ee6c040e8b6bf3cf7d to your computer and use it in GitHub Desktop.
Ensure a managed config block exists exactly once in a file (idempotent).
# Ensure a managed config block exists exactly once in a file (idempotent).
# - If the block already exists (identified by begin/end marker lines), it is replaced.
# - If it doesn't exist, it is appended.
# - Works for root-owned files via sudo by writing to a temp file then installing.
# - Callers do not need a trailing newline in <content>.
#
# Usage:
# ensure_block <file> <id> <content> [sudo]
#
# # Append (or replace) a managed block containing 'export FOO=bar' in
# # ~/.bash_profile, identified by the tag "dotfiles/env":
# ensure_block "$HOME/.bash_profile" "dotfiles/env" 'export FOO=bar'
#
# # Same idea but multi-line content and a root-owned file — use $'...\n...'
# # quoting and pass "sudo" as the fourth argument:
# ensure_block "/etc/hosts" "devenv/local-dns" $'127.0.0.1 example.local\n::1 example.local' sudo
#
ensure_block() {
if [ "$#" -lt 3 ] || [ "$#" -gt 4 ]; then
printf 'usage: ensure_block <file> <id> <content> [sudo]\n' >&2
return 2
fi
local file="$1"
local id="$2"
local content="$3"
local use_sudo="${4:-}"
local begin="# >>> managed by ${id} >>>"
local end="# <<< managed by ${id} <<<"
local tmp
tmp="$(mktemp)"
{
# Read existing file if present, else start empty
if [ -f "$file" ]; then
# Strip any existing managed block for this id
awk -v b="$begin" -v e="$end" '
$0==b {skip=1; next}
$0==e {skip=0; next}
!skip {print}
' "$file" >"$tmp" || return 1
else
: >"$tmp"
fi
# Trim trailing blank lines so the separator doesn't grow on re-runs
if [ -s "$tmp" ]; then
printf '%s\n' "$(< "$tmp")" >"$tmp"
fi
# Append the desired block exactly once (with a leading blank line if file non-empty)
if [ -s "$tmp" ]; then
printf '\n' >>"$tmp"
fi
printf '%s\n' "$begin" >>"$tmp"
printf '%s\n' "$content" >>"$tmp"
printf '%s\n' "$end" >>"$tmp"
# Install back (atomic-ish), preserving permissions if file exists; else default 0644
local mode="0644"
if [ -f "$file" ]; then
local m
m="$(stat -c %a "$file" 2>/dev/null || stat -f %Lp "$file" 2>/dev/null || true)"
[ -n "${m:-}" ] && mode="$m"
fi
if [ -n "$use_sudo" ]; then
sudo install -m "$mode" "$tmp" "$file"
else
install -m "$mode" "$tmp" "$file"
fi
} always {
rm -f "$tmp"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment