Linux Atomic File Rename: Safely Update Config Files

Quick Linux Tip #119:

Question: My config reload reads a half-written file. How do I update it safely?

Try: mv /etc/myapp/config.new /etc/myapp/config.json

Info: Same-filesystem file renames are atomic at the inode level, ensuring readers see either the complete old file or the new file.

Examples:

  • $ sed -i.bak 's/old/new/' file  # Perform an in-place file edit with an automatic backup
  • $ python3 -c 'import os; os.rename("new.conf", "live.conf")'  # Execute an atomic rename using Python
  • $ install -m 644 new.conf /etc/live.conf  # Safely copy a new configuration file while enforcing permissions

Note: Atomicity only applies within the same filesystem (cross-filesystem moves fall back to a copy-and-delete operation). Writing to a temporary file and renaming it is the standard safe pattern for configs and databases.




LinuxTeck.com
linuxteck:~$ mv /etc/myapp/config.new /etc/myapp/config.json

linuxteck:~$ stat -c '%i %n' /etc/myapp/config.json
524295 /etc/myapp/config.json

linuxteck:~$ cat > /etc/myapp/config.new <<'EOF'
{
"version": 2,
"debug": false,
"port": 8080
}
EOF

linuxteck:~$ mv /etc/myapp/config.new /etc/myapp/config.json

linuxteck:~$ stat -c '%i %n' /etc/myapp/config.json
524301 /etc/myapp/config.json
linuxteck:~$

PREVIOUS ARTICLE Quick Linux Tip #118: Linux Directory Comparison: 3 Commands to Verify Folders NEXT ARTICLE Quick Linux Tip #120: Linux Find Rogue Network Connections: Identify and Stop Them
About John Britto

John Britto Founder & Chief-Editor @LinuxTeck. A Computer Geek and Linux Intellectual having more than 20+ years of experience in Linux and Open Source technologies.

View all posts by John Britto →

Leave a Reply

Your email address will not be published.