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 --reflink=always makes an instant copy on Btrfs and XFS, or fails

Linux
~/tips/tip-linux-cp-reflink

cp --reflink=always vdisk1.img vdisk1-before-update.img

Clones a big file in an instant on filesystems that support copy on write.

Copying a 40 GB VM image on a Btrfs pool doesn’t have to take minutes. Btrfs and XFS can make a clone that shares the data blocks with the original, and GNU cp knows how to ask for one.

A reflink copy only writes new metadata. The data blocks stay shared until one of the two files changes, and then only the changed blocks get their own copy. That’s copy on write, the same trick snapshots use. To demand a clone and nothing else:

cp --reflink=always vdisk1.img vdisk1-before-update.img

I like always for this because it tells you where you stand. If the filesystem can’t clone, or the two paths are on different filesystems, cp prints an error and exits with a failure status instead of silently starting a slow full copy. --reflink=never forces a normal copy.

You may already be getting clones without asking. Since coreutils 9.0, plain cp uses --reflink=auto by default: try a clone, fall back to a normal copy when that doesn’t work. Ubuntu 22.04 still ships 8.32, so there you have to pass the flag yourself. Unraid can format a cache pool as Btrfs, and on such a pool this is the quickest way I know to keep a copy of a VM disk before touching the guest.

The caveat is in the GNU manual: a clone shares its data blocks with the original as long as neither is modified, so if an I/O error hits those blocks, both files are damaged. A reflink copy protects you from your own mistakes inside the file. It does nothing against a failing disk, so it doesn’t count as a backup.

Further reading: cp(1) manual page, ioctl_ficlone(2) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link