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

例子:

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

当前回答

Shell函数,做你想要的,称它为“埋葬”副本,因为它为文件挖了一个洞:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }

其他回答

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

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

简单的

cp -a * /path/to/dst/

应该能行。

仅适用于macOS

rsync -R <source file path> destination_folder

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

这适用于MacOS上的GNU /bin/bash版本3.2(在Catalina和Big Sur上都进行了测试)

cp -Rv <existing-source-folder>/   <non-existing-2becreated-destination-folder>

“v”选项表示冗长。

我认为"-R"选项是"递归"

人类对-R的完整描述是:

If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself. This option also causes symbolic links to be copied, rather than indirected through, and for cp to create special files rather than copying them as normal files. Created directories have the same mode as the corresponding source directory, unmodified by the process' umask. In -R mode, cp will continue copying even if errors are detected. Note that cp copies hard-linked files as separate files. If you need to preserve hard links, consider using tar(1), cpio(1), or pax(1) instead.

在下面的例子中,我在existingfolder的末尾使用了一个“/”,这样它就会将existingfolder的所有内容(而不是文件夹本身)复制到newfolder中:

cp -Rv existingfolder/  newfolder

试一试。

我强烈建议你也这么做。 只是工作。

同样,my/location/poo .txt this/doesn /exist/yet/poo .txt