hn.today

Overlooked Linux Mv Option Replaces Three Commands with One

itsfoss.com18 points1 comments
Screenshot of Overlooked Linux Mv Option Replaces Three Commands with One

GNU coreutils 9.5 introduced an `mv --exchange` option that swaps two existing paths in one operation, avoiding the traditional sequence of three moves and a temporary filename. That older method can briefly leave one name missing and may leave the swap incomplete if a command fails. On Linux, `--exchange` uses the kernel’s `renameat2()` system call with `RENAME_EXCHANGE`, making the name swap atomic: both paths remain present throughout. For example, exchanging `nginx.conf` and `nginx.conf.new` puts the new configuration in the first location while preserving the old one under the second name; running the command again reverses the change.

The option also works for directories, allowing whole directory trees - such as a live release and a newly deployed version - to trade names without moving their contents. When both arguments are existing directories, add `-T` so `mv` treats the second argument as a path to exchange rather than a destination directory. Both paths must be on the same filesystem, and that filesystem must support the operation; ext4, Btrfs, XFS, and tmpfs are listed as supported examples. Cross-filesystem exchanges fail because copying and deleting would not be atomic. Check availability with `mv --version` or `mv --help`; systems with GNU coreutils 9.5 or later, including recent NixOS, Fedora, and Debian 13 installations, may provide it.

Read on itsfoss.com1 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.