views:

1222

answers:

2

Linux: I want a command (or probably an option to cp) that creates the destination directory if it does not exist.

Example:

cp -? file /path/to/copy/file/to/is/very/deep/there
+12  A: 
test -d "$d" || mkdir -p "$d" && cp file "$d"

(there's no such option for cp).

Michael Krelin - hacker
I don't think you need the `test -d`: `mkdir -p` still succeeds even if the directory already exists.
ephemient
oops, right. But then, test may be a bash builtin (especially if written as [[ -d "$d" ]]) and mkdir can not ;-)
Michael Krelin - hacker
`mkdir` is a builtin in BusyBox ;)
ephemient
ephemient, true ;-)
Michael Krelin - hacker
A: 

Shell function that does what you want, calling it a "bury" copy because it digs a hole for the file to live in:

bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
Andy Ross
You should have quotation marks around the ``dirname $2`` too
Kalmi