我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
我需要一个命令(可能是cp的一个选项)来创建目标目录(如果目标目录不存在)。
例子:
cp -? file /path/to/copy/file/to/is/very/deep/there
当前回答
这适用于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
试一试。
其他回答
仅适用于macOS
rsync -R <source file path> destination_folder
对于macOS -父母cp选项不工作
这对我来说很有用
cp -vaR ./from ./to
我强烈建议你也这么做。 只是工作。
同样,my/location/poo .txt this/doesn /exist/yet/poo .txt
简短的回答
复制myfile.txt到/foo/bar/myfile.txt,使用:
mkdir -p /foo/bar && cp myfile.txt $_
这是如何工作的呢?
这里有几个组件,所以我将一步一步地介绍所有语法。
POSIX标准中指定的mkdir实用程序创建目录。根据文档,-p参数将导致mkdir
创建任何缺少的中间路径名组件
这意味着当调用mkdir -p /foo/bar时,如果/foo不存在,mkdir将创建/foo和/foo/bar。(如果没有-p,它将抛出一个错误。
&&列表操作符,如POSIX标准(或Bash手册,如果你喜欢)中所述,其效果是只有在mkdir -p /foo/bar成功执行时才执行cp myfile.txt $_。这意味着如果mkdir失败,cp命令将不会尝试执行,原因有很多。
最后,我们传递给cp的第二个参数$_是一个“特殊参数”,可以方便地避免重复长参数(如文件路径),而不必将它们存储在变量中。根据Bash手册,它:
展开到上一个命令的最后一个参数
在本例中,这是我们传递给mkdir的/foo/bar。因此cp命令展开为cp myfile.txt /foo/bar,将myfile.txt复制到新创建的/foo/bar目录中。
注意$_不是POSIX标准的一部分,所以理论上Unix变体可能有一个不支持这个构造的shell。然而,我不知道任何现代shell不支持$_;当然Bash, Dash和zsh都喜欢。
最后注意:我在回答开头给出的命令假设目录名中没有空格。如果你正在处理带有空格的名称,你需要引用它们,这样不同的单词就不会被视为mkdir或cp的不同参数。所以你的命令实际上是这样的:
mkdir -p "/my directory/name with/spaces" && cp "my filename with spaces.txt" "$_"
这里有一种方法:
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上运行。