My understanding of cp src dest is:
- If
srcis a file anddestdoesn't exist, but its parent directory does,destis created. - If
srcis a file anddestis a file,destis overwritten with the contents ofsrc. - If
srcis a file anddestis a directory,dest/srcis created.
I'm trying to avoid case #3. If I write a script assuming that dest won't be a directory, but it turns out at runtime that it is, I don't want cp to put a file in the wrong place and continue silently.
Instead, I want it to either:
- Delete the whole
destdirectory and replace it with the desired file. - Error out without doing anything.
I'd also prefer for this to happen atomically. Using a separate command like test -d to check if dest is a directory would open up an opportunity for TOCTTOU problems.
Can this be done with cp? If not, can it be done with any other similarly ubiquitous command?
I'm interested in both portable solutions and solutions that rely on non-standard extensions, as long as they're reasonably common.
-T, --no-target-directorywould do what you want. What implementation of cp do you use then? – Arkadiusz Drabczyk Jan 04 '21 at 18:38cp. – Maxpm Jan 04 '21 at 19:16