「关于使用mv命令合并目录」

经常会有这种情景:我们需要合并两个目录。

实际情况:mv命令不支持目录合并

看一个示例。当前目录下有两个目录a0与b0,同时b0中还有一个a0,但是这个两个a0目录的内容不同,我想合并这两个a0目录。目录结构如下:

# tree a0 b0

a0

└── a1
├── a1.txt

└── a2
b0

├── a0

│   └── a1

│   └── a2

│   └── a2.txt

└── b1
└── b2

7 directories, 2 files

在我尝试将a0合并到b0/a0中时,mv命令返回了一个错误:

# mv a0 b0/

mv: cannot move ‘a0’ to ‘b0/a0’: Directory not empty

之所以返回这个错误是因为mv命令不支持目录合并

实现目录合并的方法

不跨文件系统的解决方案

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

Notes:

  1. 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.
  2. 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.
  3. This does not work if your source and destination folders are on different filesystems

其他解决方案

BASH – merge directories when using mv
Merging folders with mv?

参考文献

BASH – merge directories when using mv
Merging folders with mv?