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

例子:

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

当前回答

虽然已经很晚了,但对新手还是有帮助的。如果你需要自动创建文件夹,rsync应该是你最好的朋友。

rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/

其他回答

如果以下两个条件都成立:

您使用的是GNU版本的cp(而不是Mac版本),并且 您正在从一些现有的目录结构进行复制,您只需要重新创建它

然后你可以用cp的——parents标志来做。从信息页面(可以在http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation或info cp或man cp查看):

——父母 通过追加到目标文件来形成每个目标文件的名称 目录中包含斜杠和源文件的指定名称。的 给' cp'的最后一个参数必须是现有的 目录中。例如,命令: Cp——parents a/b/c existing_dir 复制文件' a/b/c'到' existing_dir/a/b/c',创建any 缺少中间目录。

例子:

/tmp $ mkdir foo
/tmp $ mkdir foo/foo
/tmp $ touch foo/foo/foo.txt
/tmp $ mkdir bar
/tmp $ cp --parents foo/foo/foo.txt bar
/tmp $ ls bar/foo/foo
foo.txt

install -D file -m 644 -t /path/to/copy/file/to/is/very/deep/there

仅适用于macOS

rsync -R <source file path> destination_folder

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

虽然已经很晚了,但对新手还是有帮助的。如果你需要自动创建文件夹,rsync应该是你最好的朋友。

rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/

简单的

cp -a * /path/to/dst/

应该能行。