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: mv --exchange swaps two files or folders in one atomic step

Files
~/tips/tip-linux-mv-exchange

mv -T --exchange /srv/site/html /srv/site/html-new

Swaps the names of two files or directories at once, with nothing in between.

Swapping two files used to mean three renames and a temporary name in between. Since coreutils 9.5, GNU mv can do it in one go, and I think it’s one of the nicer additions to a tool that hadn’t changed much in years.

mv --exchange A B trades the two names: what was A is now called B and the other way round. Both have to exist, and they don’t need to be the same type, so a folder and a symlink can trade places too. For two directories, add -T (--no-target-directory) so mv doesn’t read B as a place to move A into:

mv -T --exchange /srv/site/html /srv/site/html-new

After that, the new build is live under html and the old one waits in html-new. Run the same command again to roll back. The manual says the exchange is atomic when both paths are on one filesystem that supports it, so a web server reading the folder sees either the old version or the new one, never half of each. Under the hood it’s the RENAME_EXCHANGE flag of the kernel’s renameat2() call.

The catch is the version. Ubuntu 24.04 ships coreutils 9.4, so its mv doesn’t know the option yet, while Debian 13 has 9.7. Check mv --version first. The exchange also doesn’t work across filesystems: the manual says non-atomic exchanges are not supported yet, and suggests --no-copy in scripts so a future version never falls back to copying. And on a FUSE mount such as an Unraid user share I wouldn’t count on the kernel flag being supported at all.

Further reading: mv(1) manual page, rename(2): RENAME_EXCHANGE

More Files tips sha256sum -c --ignore-missing SHA256SUMS xxhsum -H64 backup.tar > backup.xxh unzip -j archive.zip -d out/ Files > More > Select > pick files > More > Compress ls -lhS /var/log All Files tips (15) All topics

Link