Why is mv so much faster than cp? How do I recover from an incorrect mv command?

If a directory is moved within the same filesystem (the same partition), then all that is needed is to rename the file path of the directory. No data apart from the directory entry for the directory itself has to be altered.

When copying directories, the data for each and every file needs to be duplicated. This involves reading all the source data and writing it at the destination.

Moving a directory between filesystems would involve copying the data to the destination and removing it from the source. This would take about as long time as copying (duplicating) the data within a single filesystem.


If FileZilla successfully renamed the directory from ~/big_folder to ~/some_other_folder/big_folder, then I would revert that using

mv ~/some_other_folder/big_folder ~/big_folder

... after first making sure that there were no directory called ~/big_folder (if there was, the move would put big_folder from some_other_folder into the ~/big_folder directory as a subfolder).


The existing answer is great, but I'd like to expand on it a bit by showing exactly what is happening when you move versus when you copy a file. When you look at the syscalls during a copy, you see:

open("hello1.txt", O_RDONLY)               = 3
open("hello2.txt", O_WRONLY|O_CREAT, 0644) = 4
read(3, "Hello, world!\n", 4096)           = 14
write(4, "Hello, world!\n", 14)            = 14
close(3)                                   = 0
close(4)                                   = 0

This opens the source file, then creates a second file. It then reads the contents of the source file to memory and writes that memory to the destination file. This requires several context switches and some disk I/O which can be quite high for large files. If you move a file however, you see:

rename("hello1.txt", "hello2.txt")         = 0

It's important to remember that you will only see the file be renamed if it is on the same partition on the same physical disk. If you create a huge, multi-gigabyte file and then move it between two locations in your home, you will notice the action completes instantly. If, on the other hand, you move it to an external device, it will take as long to move as if you used cp instead. This is because moving a file can only be done by renaming it if it is on the same partition.

Tags:

Mv

Cp

File Copy