关于linux:Linux技巧cp命令自动创建不存在的目录和只复制修改的文件

1次阅读

共计 1541 个字符,预计需要花费 4 分钟才能阅读完成。

复制时主动创立不存在的子目录

在 Linux 中,能够应用 cp 命令的 --path 选项指定在复制的时候主动创立不存在的子目录。

例如执行上面的命令:

$ cp --path java/com/server/Service.java target/

如果 target 目录下不存在 java/com/server/ 这一串子目录,cp --path 命令会主动创立 java/com/server/ 这一串子目录,而后把文件复制到对应的子目录下。

留神 :在下面命令中,target 目录必须存在,能力复制。cp --path 命令只会主动创立源文件门路蕴含的子目录,不会主动创立所给的目标目录。

从行为来看,cp --path java/com/server/Service.java target/ 命令相似于上面的命令:

$ mkdir -p target/java/com/server/
$ cp java/com/server/Service.java target/java/com/server/

mkdir -p 命令示意递归创立一串子目录。

–parents 选项

查看 man cp 的阐明,外面没有提到 --path 选项,但实际上能够应用这个选项。它应该是被废除了。

应用该选项复制报错时,提醒的选项名是 --parents,应该是被 --parents 选项所代替:

$ cp --path java/com/server/Service.java not_exist/
cp: with --parents, the destination must be a directory
Try 'cp --help' for more information.

能够看到,cp --path 命令复制报错,提示信息说是应用 --parents 时,指标文件名必须是一个曾经存在的目录。

可见,--path 被当成 --parents 来解决。

查看 GNU cp 的在线帮忙链接 https://www.gnu.org/software/…,对 --parents 选项阐明如下:

–parents

Form the name of each destination file by appending to the target directory a slash and the specified name of the source file.

The last argument given to cp must be the name of an existing directory. For example, the command:

    cp --parents a/b/c existing_dir

copies the file a/b/c to existing_dir/a/b/c, creating any missing intermediate directories.

即,当被复制的源文件门路蕴含子目录名,--parent 选项会在目标目录下主动创立不存在的子目录。目标目录自身必须曾经存在。

因为在 cp 命令的帮忙信息中曾经找不到 --path 选项的阐明,倡议不再应用这个选项,改用 --parents 选项。

只复制新批改过或者不存在的文件

在 Linux 中,有时候会遇到这样一个问题场景:应用 cp 命令复制一个很大的目录(该目录底下有很多子目录或者文件),然而复制到中途时,遇到异样,导致进行复制,须要从新复制。

这个时候不心愿复制曾经复制过的文件,而是只复制还没有复制过的文件。那么能够应用 cp 命令的 -u 选项。

查看 man cp 对 -u 选项阐明如下:

-u, –update

copy only when the SOURCE file is newer than the destination file or when the destination file is missing.

即,只有源文件新于指标文件、或者指标文件不存在时,cp -u 命令才会复制这个文件。

正文完
 0