I'm trying to copy a file only if it already exists, not if it doesn't, basically overwrite only on Linux. Does anyone know a solution?

I basically need to "look" for a folder then if a file exists, it overwrites in destination (recursive)


Although there's a small race condition you could use something like this:


[[ -f "$dst" ]] && cp -fp "$src" "$dst"

The [[ ... ]] operations checks to to see if the file already exists, and if it does the && allows the copy to proceed.

If you have rsync you can do it directly (the --existing flag tells rsync only to update files that already exist):

rsync --existing --archive "$src" "$dst"
\cp -rf source destination

overwrites if file exists without confirmation

  • 2
    It will also copy the file if the target doesn't exist, which is what the OP wants to avoid. – xenoid May 16 at 15:15
  • 1
    This is an incorrect answer to the question the OP has asked. – 0xSheepdog May 16 at 15:20
  • the source must be fresh >filelist.txt. that kind of blind copy/sync is incorrect. – studen May 26 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.