How to copy into with cp if destination folder already exists?

Example...

This is what I want.

/tmp $ cp -f -R --verbose /tmp/a /tmp/b
`/tmp/a' -> `/tmp/b'
`/tmp/a/file2' -> `/tmp/b/file2'
`/tmp/a/file1' -> `/tmp/b/file1'

This is what I do not want.

/tmp $ cp -f -R --verbose /tmp/a /tmp/b
`/tmp/a' -> `/tmp/b/a'
`/tmp/a/file2' -> `/tmp/b/a/file2'
`/tmp/a/file1' -> `/tmp/b/a/file1'

How can I let cp behave as if the folder didn't already exist?

(I don't want to delete it beforehand. Just some files from /tmp/a to get copied into /tmp/b without creating a sub folder a inside /tmp/b. So it looks like /tmp/b/file1 /tmp/b/file2 and so on.)


The -T flag (AKA --no-target-directory) does what you want:

$ cp -R --verbose -T /tmp/a /tmp/b
`/tmp/a/file1' -> `/tmp/b/file1'
`/tmp/a/file2' -> `/tmp/b/file2'

Assuming Bash you can do

( shopt -s dotglob; cp -f -R --verbose /tmp/a/* /tmp/b/ )

What this does is:

  1. it will make sure globs (the *) catch files with a dot in front. They are considered "hidden" by convention.
  2. * will expand before cp gets to see the command. So if there are two files as in your question the expanded command line will be cp -f -R --verbose /tmp/a/file1 /tmp/a/file1 /tmp/b/
  3. finally the trailing backslash on the destination makes sure that it copies into that folder /tmp/b/.

This method also makes sure you don't have to reset the shell option, because it's being run in a subshell. You can achieve similar results by putting it into a script file instead of executing from the command line.


Rsync was invented for this kind of thing.

rsync -av --update /source/ /destination

NB: Notice that /source/ has a trailing "/" which picks up file1, file2 and not the folder it is in. /destination doesnt have a trailing. So your solution looks like this:

rsync -av --update /tmp/a/ /tmp/b