This Overlooked Linux mv Option Replaces Three Commands With One
Every Linux user has done the three-step dance at least once. You want to swap two files, so you move the first one to a temporary name, move the second one into its place, and then move the temporary file back.
Ever felt that this is a bit... clumsy? And for a moment, one of your files simply doesn't exist. That doesn't feel right!
Since version 9.5, GNU coreutils has a better way: mv --exchange .
In this article, I'll show you what it does, how to check if your system has it, where it actually helps, and the mistake I made the first time I used it on directories.
The old way: three moves and a temporary name
Let's say you have two configuration files, nginx.conf and nginx.conf.new , and you want the new one to take the place of the old one while keeping the old one around.
The classic approach looks like this with the mv command :
mv nginx.conf nginx.conf.tmp
mv nginx.conf.new nginx.conf
mv nginx.conf.tmp nginx.conf.new
There are two problems here:
There is a gap. Between the first and second command, nginx.conf doesn't exist. If a service reads it at that exact moment, it finds nothing (and trust me, one day that will happen).
It can fail halfway. If the second command fails, you are left with a temporary file and a half-finished swap to clean up by hand.
The exchange option does this in a single command:
mv --exchange nginx.conf nginx.conf.new Swap files with mv --exchange
The --exchange option tells mv to swap the two paths in a single operation. On Linux, it uses the kernel's renameat2() system call with the RENAME_EXCHANGE flag, so the swap is atomic: at any moment, both names exist and point to a file.
Check if your mv supports it
First, check your coreutils version:
mv --version
On my machine, running NixOS , I get:
mv (GNU coreutils) 9.11
You need version 9.5 or newer. Careful here: version numbers are not decimals. They are compared part by part, so 9.11 (nine point eleven) is newer than 9.5. You can also check whether the option is listed in the help:
mv




Comments
No comments yet. Be the first to share your thoughts.