This question already has an answer here: 这个问题在这里已有答案:
When copying a file using cp
to a folder that may or may not exist, how do I get cp
to create the folder if necessary? 使用cp
将文件复制到可能存在或不存在的文件夹时,如何在必要时获取cp
来创建文件夹? Here is what I have tried: 这是我尝试过的:
[root@file nutch-0.9]# cp -f urls-resume /nosuchdirectory/hi.txt
cp: cannot create regular file `/nosuchdirectory/hi.txt': No such file or directory
#1楼
参考:https://stackoom.com/question/3yba/如何让cp命令创建任何必要的文件夹以将文件复制到目标-重复
#2楼
也可以使用命令find
:
find ./ -depth -print | cpio -pvd newdirpathname
#3楼
For those that are on Mac OSX, perhaps the easiest way to work around this is to use ditto (only on the mac, AFAIK, though). 对于那些使用Mac OSX的人来说,解决这个问题的最简单方法可能就是使用ditto (仅限于mac,AFAIK)。 It will create the directory structure that is missing in the destination. 它将创建目标中缺少的目录结构。
For instance, I did this 例如,我这样做了
ditto 6.3.2/6.3.2/macosx/bin/mybinary ~/work/binaries/macosx/6.3.2/
where ~/work
did not contain the binaries directory before I ran the command. 在运行命令之前, ~/work
没有包含二进制目录。
I thought rsync should work similarly, but it seems it only works for one level of missing directories. 我认为rsync应该工作类似,但它似乎只适用于一个级别的丢失目录。 That is, 那是,
rsync 6.3.3/6.3.3/macosx/bin/mybinary ~/work/binaries/macosx/6.3.3/
worked, because ~/work/binaries/macosx existed but not ~/work/binaries/macosx/6.3.2/ 工作,因为〜/ work / binaries / macosx存在但不是〜/ work / binaries / macosx / 6.3.2 /
#4楼
To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir
and cp
: 为了扩展Christian的答案,唯一可行的方法是将mkdir
和cp
结合起来:
mkdir -p /foo/bar && cp myfile "$_"
As an aside, when you only need to create a single directory in an existing hierarchy, rsync
can do it in one operation. 另外,当您只需要在现有层次结构中创建单个目录时, rsync
可以在一个操作中执行此操作。 I'm quite a fan of rsync
as a much more versatile cp
replacement, in fact: 我非常喜欢rsync
作为一个更通用的cp
替代品,事实上:
rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't. bar is created.
#5楼
cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory
It will create no existing paths in destination, if path have a source file inside. 如果路径中包含源文件,它将在目标中不创建现有路径。 This dont create empty directories. 这不会创建空目录。
A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. 刚才我见过xxxxxxxx:没有这样的文件或目录,因为我用完了空闲空间。 without error message. 没有错误消息。
with ditto: 与同上:
ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device
once freed space cp -Rvn /source/path/* /destination/path/
works as expected 一旦释放空间cp -Rvn /source/path/* /destination/path/
按预期工作
#6楼
rsync is work! rsync是有效的!
#file:
rsync -aqz _vimrc ~/.vimrc
#directory:
rsync -aqz _vim/ ~/.vim