Is there some difference between mv and {cp + rm the old file} on Unix?

Solution 1:

Assuming the files involved are on the same file system, then mv simply changes pointers in the file system, whereas cp copies the entire contents of the file, and rm once again changes pointers. So mv is far more efficient.

Solution 2:

Yes, mv has a chance of being atomic on the same disk, whereas the combination of cp and rm never has.

This is assuming that mv is implemented using rename(), which is the call that has the guarantee. See, for instance, this newsgroup post, which quotes POSIX:

This rename() function is equivalent for regular files to that defined by the ISO C standard. Its inclusion here expands that definition to include actions on directories and specifies behavior when the new parameter names a file that already exists. That specification requires that the action of the function be atomic.

Solution 3:

On the same file system mv changes the directory reference, pointing to the same inode (file data and metadata) thus:

  • is an atomic operation (it cannot be interrupted by another process file operation)
  • takes only a trivial amount of additional disk space (the additional name in the directory)
  • preserves file permissions and ownership
  • can be much faster, depending on amount of data

Copy and remove

  • is not atomic (another process could interfere between the cp and rm commands)
  • requires storing the file data twice on disk for a short period (between the cp and rm commands)
  • changes file permissions and ownership to defaults
  • can be much slower or even fail, depending on amount of data

Solution 4:

When the source and the destination are on the same physical volume, then the first approach is simply a rename and is very fast (even if the file(s) are very big).

cp & rm will always have to load/store all the data, even if it weren't necessary.