Bash

Atomic File Write (write then rename)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Write to a temp file in the SAME directory, then `mv` to the final name. mv on the same filesystem is atomic — readers never see a half-written file.
Bash
Raw
atomic_write() {
    local target="$1" content="$2"
    local dir
    dir="$(dirname "$target")"
    local tmp
    tmp="$(mktemp "$dir/.$(basename "$target").XXXXXX")"
    printf '%s' "$content" > "$tmp"
    mv "$tmp" "$target"           # atomic on POSIX, same filesystem
}

# Usage
atomic_write /var/lib/myapp/state.json '{"ready": true}'

# Concurrent-safe pattern for cron jobs writing the same file:
update_status() {
    local out="/var/lib/myapp/status.txt"
    atomic_write "$out" "Last run: $(date -u +%FT%TZ)"
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.