My understanding of cp src dest
is:
- If
src
is a file anddest
doesn't exist, but its parent directory does,dest
is created. - If
src
is a file anddest
is a file,dest
is overwritten with the contents ofsrc
. - If
src
is a file anddest
is a directory,dest/src
is 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
dest
directory 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-directory
would 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