How to fix “Directory not empty” when using mv in Linux

mv (or move) is a Unix/Linux command that moves one or many files or directories from one place to another.

mv is usually used for two purposes:

  • It rename a file or folder.
  • It moves group of files to different directory.

mv syntax and usage should be straightforward. However, when you’re learning to use Linux for the first time or when you’ve come to Linux with a solid background in another operating system, you may run into some things that it doesn’t allow.

If you’ve ever received a Directory not empty when trying to move files or directories, then this guide can help you.

Why does “Directory not empty” happens?

This is one of the most common errors with mv. Usually, Directory not empty occured when you’re moving directories, and the target directory already contains files.

$ mv network_files/ tax_network mv: cannot move `network_files/' to `tax_network/network_files': Directory not empty

You can try --force trying to overwrite files and directories without explicit permission like this, but it won’t work either.

$ mv --force network_files/ tax_network mv: cannot move `network_files/' to `tax_network/network_files': Directory not empty

mv, as its name suggests, do one thing and one thing only : move files and directories (also rename them, which is another way of saying move).

This is mv‘s built-in protective mechanism to prevent you from accidentally use mv for purposes it isn’t built for. It refuses to work in this case because you’re merging contents of one directory to another.

How to move files/directories to a non-empty directory

Having known the cause of the error, we have several ways to do what we intended to do.

Method 1 : Using rsync

One of the best way is using rsync instead. rsync is built for copying files from source to destination, and have the ability to retain the attributes of many files and folders. Overall, rsync is better than cp because it only copies the files that is not present in the target directory instead of all files.

Enter this command to your terminal to sync contents from source to target :

rsync -a source/ target/

After that, removes the source directory by :

rm -rf source/*

Method 2 : Using built-in commands

Instead of using rsync, you also can do this classical command which earns you more geek points. It’s quick and dirty, if you know what you are doing:

(cd backup && tar c .) | (cd backupArchives && tar xf -)