Connecting Tech Pros Worldwide Help | Site Map

force cp to overwrite existing directory

bilibytes's Avatar
Familiar Sight
 
Join Date: Jun 2008
Location: Europe
Posts: 128
#1: Mar 4 '09
hi there,

i am fighting against my unix box to be able to copy a directory and replace the destination if already existing.
i'm using "Bash"

i use:

Expand|Select|Wrap|Line Numbers
  1. cp -fR /source/src_directory /destination/dest_directory
what this will do is that it will create a directory like this:
(assuming destination/dest_directory already exists)
Expand|Select|Wrap|Line Numbers
  1. /destination/dest_directory/dest_directory
and i want:

Expand|Select|Wrap|Line Numbers
  1. /destination/dest_directory
if you know how to obtain the last result please let me know, because i wont be able to sleep until then! lol

thank you

best regards

bilibytes
bilibytes's Avatar
Familiar Sight
 
Join Date: Jun 2008
Location: Europe
Posts: 128
#2: Mar 4 '09

re: force cp to overwrite existing directory


I came with sort of a patch solution:

in my .profile under the home directory, i created a function: cpForce which looks like this:

cpForce(){
sudo rm -fR $1
sudo cp -fR $1
}


regards.
Familiar Sight
 
Join Date: Apr 2007
Posts: 188
#3: Mar 4 '09

re: force cp to overwrite existing directory


I think it would be sufficient to do

Expand|Select|Wrap|Line Numbers
  1. cp -fR source/src_directory destination/
That is, don't specify the destination directory, just the path up to it (if that makes sense). So if you have

/source/files/filetocopy
/source/files/filetocopy2
/dest/files

you just do

Expand|Select|Wrap|Line Numbers
  1. cp -fR /source/files /dest
and you end up with

/source/files/filetocopy
/source/files/filetocopy2
/dest/files/filetocopy
/dest/files/filetocopy2

Maybe I'm not understanding your issue though.
bilibytes's Avatar
Familiar Sight
 
Join Date: Jun 2008
Location: Europe
Posts: 128
#4: Mar 7 '09

re: force cp to overwrite existing directory


ok thanks, i now understood the problem.

The first time you copy a folder to another directory, if the folder does not exist in the directory, you have to specify the name of the folder as:

cp -fR /source_directory/folder /destination_directory/folder

and it will copy the /source_directory/folder as /destination_directory/folder.

However the second time, /destination_directory/folder already exists and running the same command will do this:

/destination_directory/folder/folder

so it copies the folder inside the first copied folder.

and that is the weird thing.

but the destination I see that folder must be the final folder -1
however if you want the destination folder to have a different name than the source my alias in the post above works fine.

regards
Reply