brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: cp --backup=numbered keeps the file you were about to overwrite

Backup
~/tips/tip-linux-cp-backup-numbered

cp --backup=numbered nginx.conf /etc/nginx/nginx.conf

Saves every overwritten file as a numbered copy, so you can always go back.

Copying a new config over an old one is the kind of move I only regret afterwards. GNU cp can save the old version for you first, and I’d add it to any script that writes over files that already exist.

With --backup, cp renames the existing destination before it writes the new file. Add =numbered and every old version gets its own number, so a second copy doesn’t wipe out the first backup:

cp --backup=numbered nginx.conf /etc/nginx/nginx.conf

Run that a few times and the folder holds nginx.conf next to nginx.conf.~1~, nginx.conf.~2~ and so on. The highest number is the version you replaced most recently, so getting it back is a plain cp or mv in the other direction.

The short -b takes no value and uses the existing method: numbered backups for files that already have them, a simple backup with a tilde (nginx.conf~) for the rest. -S .bak swaps the tilde for a suffix of your choice, and the VERSION_CONTROL environment variable sets the default method once, for example export VERSION_CONTROL=numbered in a script. The same options work on mv, ln and install, which is handy when a deploy script moves a new file into place.

The catch is that numbered backups never clean themselves up. Put this in a cron job that copies the same file every hour and you’ll have hundreds of ~N~ files sitting next to it. My advice is to use it for changes you make by hand and for scripts that run now and then, and to clear out the old numbers once you’re happy with the new version.

Further reading: cp(1) manual page, GNU coreutils: Backup options

More Backup tips restic snapshots --group-by host,paths mysqldump --routines --events mydb > mydb.sql rsync -a --files-from=list.txt /home/me/ backup:/backup/ restic find "*.txt" restic stats All Backup tips (45) All topics

Link