How to have the cp command create any necessary folders for copying a file to a destination

omg picture omg · Jun 4, 2009 · Viewed 506k times · Source

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? 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

Answer

lhunath picture lhunath · Dec 29, 2012

To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir and 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. I'm quite a fan of rsync as a much more versatile cp replacement, in fact:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't.  bar is created.