how is cp -f different from cp --remove-destination?

17,945

Solution 1

There's a distinction between the two (emphasis mine):

if an existing destination file cannot be opened, remove it and try again
remove each existing destination file before attempting to open it

In the first case, if the file can be opened, cp will attempt to replace only the contents. cp is not going to remove the file unnecessarily. This will retain the permissions and ownerships of the original file unless you specify that they're to be copied too.

The second case is useful when the contents can't be read (such as dangling symlinks).

Solution 2

and: in case the destination file has multiple links (hardlinks), --remove-destination will not destroy the content of the other links. Instead just the link of the destination is removed (now we know, why "remove" is called "unlink" in deeper system functions) and a new file with a new inode is created.

Share:
17,945
anotherguy
Author by

anotherguy

A user of linux for work, with an avid side interest in it.

Updated on September 18, 2022

Comments

  • anotherguy
    anotherguy almost 2 years

    in the cp manpage, it lists the -f/--force option as: if an existing destination file cannot be opened, remove it and try again

    for the --remove-destination option it says: remove each existing destination file before attempting to open it (contrast with --force)

    So, the former first checks if it can be opened, if not, it deletes in anyway, while the latter just bypasses that step. I combined each with the -i option, and in both cases, it indicates what the permissions of the files are if it's write-protected.

    The latter would seem to be more efficient, especially if recursively copying/overwriting large directories, but why maintain both options? What's the advantage of checking something it's going to over-ride anyway?

  • AdminBee
    AdminBee almost 4 years
    This looks like an addendum to the accepted answer and should probably included there.