我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。

例子:

cp -? file /path/to/copy/file/to/is/very/deep/there

当前回答

简单地没有创建脚本和简单的命令…

mkdir -p /destination-folder/ && cp file-name /destination-folder/

其他回答

这里有一种方法:

mkdir -p `dirname /path/to/copy/file/to/is/very/deep/there` \
   && cp -r file /path/to/copy/file/to/is/very/deep/there

Dirname将为您提供目标目录或文件的父目录。Mkdir -p ' dirname…'将创建该目录,确保当您调用cp -r时,正确的基目录已经就位。

这相对于——parents的优点是,它适用于目标路径中的最后一个元素是文件名的情况。

它可以在OS X上运行。

我尊重上面的答案,我更喜欢使用rsync如下所示:

$  rsync -a directory_name /path_where_to_inject_your_directory/

例子:

$ rsync -a test /usr/local/lib/
rsync file /path/to/copy/file/to/is/very/deep/there

如果您有正确的rsync类型,这可能会起作用。

仅适用于macOS

rsync -R <source file path> destination_folder

对于macOS -父母cp选项不工作

简单的

cp -a * /path/to/dst/

应该能行。