LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to copy a file when destination directory does not exists. (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-copy-a-file-when-destination-directory-does-not-exists-4175429818/)

abhinav4 10-01-2012 01:00 AM

How to copy a file when destination directory does not exists.
 
Can I copy a file when destination directory does not exist. In below example i want to copy index.html to /home/www/example2 wherw example2 does not exists.

Quote:

cp /home/www/example/index.html /home/www/example2/

pan64 10-01-2012 01:13 AM

you can test it easily (no, it won't do it)
and also you can imagine, if example2 did not exist cp cannot decide: is this the target dir or target filename.

nugat 10-01-2012 01:15 AM

Quote:

Originally Posted by abhinav4 (Post 4793668)
Can I copy a file when destination directory does not exist. In below example i want to copy index.html to /home/www/example2 wherw example2 does not exists.

is there any reason you cannot use mkdir?

Code:

mkdir /home/www/example2
you can always use the install program, e.g.:

Code:

install -D /home/www/example/index.html /home/www/example2/index.html

hydraMax 10-01-2012 01:17 AM

I don't think the cp command can do that, unless I'm missing something in the manual page, though the cp command has some other interesting directory creating functionality (like the --parent command). I think you have to use mkdir -p along with the cp command, or you could create a single perl or python script to do this (which shouldn't be very difficult).

abhinav4 10-01-2012 01:56 AM

Quote:

Originally Posted by pan64 (Post 4793673)
is this the target dir or target filename.

example2 is the target directory name. I guess cp does not have the ability to create destination directory.

pan64 10-01-2012 02:09 AM

Quote:

Originally Posted by abhinav4 (Post 4793696)
example2 is the target directory name. I guess cp does not have the ability to create destination directory.

cp does not have the ability to decide if it should be a dir of file. That's why it won't create dir.

David the H. 10-01-2012 10:59 AM

You could set up a short function like this to include directory creation:

Code:

cp2dir() { mkdir -p "${!#}" && cp "$@" ;}
This will run mkdir on the final argument, and then run cp if it succeeds in creating that directory.

Note too that it will also pass through all other arguments, so the traditional cp options can still be used. But beware that it only works with the traditional cp syntax where the targetdir is the final argument, so never use the "-t/-T" options with it.

Similar functions could, of course, be set up for mv or any other command, although I don't know if I'd personally trust it with anything that could potentially destroy the original.


All times are GMT -5. The time now is 01:12 AM.