How to have the cp command create any necessary folders for copying a file to a destination [duplicate] How to have the cp command create any necessary folders for copying a file to a destination [duplicate] linux linux

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


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.


I didn't know you could do that with cp.

You can do it with mkdir ..

mkdir -p /var/path/to/your/dir

EDIT See lhunath's answer for incorporating cp.


 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt