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

例子:

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

当前回答

这么老的问题,但也许我可以提出另一种解决方案。

您可以使用安装程序复制您的文件,并“在飞行中”创建目标路径。

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

不过,还是有一些方面需要考虑的:

您还需要指定目标文件名,而不仅仅是目标路径 目标文件将是可执行的(至少,从我的测试来看)

您可以通过添加-m选项来设置目标文件的权限来轻松修改#2(例如:-m 664将创建具有权限rw-rw-r——的目标文件,就像使用touch创建一个新文件一样)。


这里有一个无耻的链接,链接到我受到启发的答案=)

其他回答

rsync file /path/to/copy/file/to/is/very/deep/there

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

只是恢复和给出一个完整的工作解决方案,在一行。 如果您想要重命名文件,请注意,您应该包括一种方法来提供到mkdir的干净dir路径。$fdst可以是file或dir。 下一段代码在任何情况下都可以工作。

fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p $(dirname ${fdst}) && cp -p ${fsrc} ${fdst}

或者特定于bash

fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p ${fdst%/*} && cp -p ${fsrc} ${fdst}

Oneliner创建一个小脚本,可以用作子命令,在find例如:

组+ H;Echo -e "#!/bin/sh\nmkdir -p \$(dirname \"\$2\");Cp \"$ 1\" \"$2\"\;"> ~ /地方/ bin / cpmkdir;Chmod +x ~/local/bin/cpmkdir . sh

然后你可以这样使用它:

查找name files_you_re_lookin_for。* -exec cpmkdir {} ./ extracted_copy / {} \;

这适用于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

试一试。

许多其他解决方案都不能用于需要转义的文件或文件夹。下面是一个解决方案,它适用于文件和文件夹,并转义空格和其他特殊字符。测试在一个繁忙箱灰壳,没有访问一些花哨的选项。

export file="annoying folder/bar.txt"
export new_parent="/tmp/"

# Creates /tmp/annoying folder/
mkdir -p "$(dirname "$new_folder/$file")"

# Copies file to /tmp/annoying folder/bar.txt
cp -r "$file" "$new_folder/$file"

如果您需要整个文件夹的递归副本而省略了bar.txt,这也可以工作。