linux - BASH - merge directories when using mv - Super User


Wed Aug 04 2021 09:39:30 GMT+0000 (Coordinated Universal Time)

Saved by @mdcx


There is a more generic discussion of this problem in the Unix section.

You can use the -l option of the cp command, which creates hard links of files on the same filesystem instead of full-data copies. The following command copies the folder source/folder to a parent folder (destination) which already contains a directory with the name folder.

cp -rl source/folder destination
rm -r source/folder

You may also want to use the -P (--no-dereference - do not de-reference symbolic links) or -a (--archive - preserve all metadata, also includes -P option), depending on your needs.
Though there are two "I/O" steps involved, the steps are relatively simple metadata operations involving zero "data" transfers. Thus this method is magnitudes faster than a cp (sans -l) or rsync-based solution.
This does not work if your source and destination folders are on different filesystems