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:Assuming Bash you can do
What this does is:
*
) catch files with a dot in front. They are considered "hidden" by convention.*
will expand beforecp
gets to see the command. So if there are two files as in your question the expanded command line will becp -f -R --verbose /tmp/a/file1 /tmp/a/file1 /tmp/b/
/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.
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:
I don't think I've seen this described anywhere; I was just trying different possibilities and found one that worked. For all I know it's a natural consequence of how
/.
andcp
work. (As opposed to the syntax forrsync
, mentioned in another answer, which is explicitly documented as a special case).