Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to cp aaa/deep/sea/blob.psd to bbb/deep/sea/blob.psd

How do I do the copy if the deep and sea directories don't exist under bbb so that the copy both creates the directories that are needed and copies the file?

Right now I get
No such file or directory as deep and sea don't exist.

I looked thru the man help pages and other questions but nothing jumps out at me.

The closest I've got is using rcp for the directory:

rcp -r aaa/deep/sea/ bbb/deep/sea/

though this copies the whole directory and contents and I just want the one file. Trying to do that however gave cp: cannot create regular file bbb/deep/sea/blob.psd' such file or directory

share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

Try to use such next function for such situation:

function copy_wdir() { mkdir -p $(dirname "$2") ; cp "$1" "$2" ; }

and use it as

copy_wdir aaa/deep/sea/blob.psd bbb/deep/sea/blob.psd

By the way cp has --parents option. It's really close to what you want, but not exactly.
It will also create aaa directory that seems you don't need. However you can first cd to aaa and copy like:

cd aaa ; cp --parents deep/sea/blob.psd ../bbb/
share|improve this answer
add comment
cd aaa
pax -rw deep/sea/blob.psd ../bbb

If you don't have pax (it's mandated by POSIX, as a standard replacement of cpio and tar which had too many incompatibilities to standardize), use cpio -p or tar -cf - … | tar -xf - instead.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.