53

How do I copy a file in Linux only when the file being copied is newer than the version at the destination?

If the file at the destination is newer, I want the file copy to not go ahead.

69

Using the update option (-u) with cp should do it for you.

http://beginnerlinuxtutorial.com/help-tutorial/basic-linux-commands/cp-linux-copy-command/

2
  • 32
    To save future readers some time: this question is tagged Linux. Non-GNU cp implementations (BSD, macOS, etc.) lack the -u option. You can use rsync --update instead.
    – user31389
    Oct 21 '16 at 13:04
  • On FreeBSD you may want to install coreutils package with pkg install coreutils. Then, among others, you will have GNU cp under the name gcp. Note that there is also brew package coreutils which also provide gcp.
    – smbear
    May 28 '20 at 9:49
26

Use rsync

rsync --progress -r -u /from/one/* /to/another/directory
2
  • 3
    Just for completeness: -r means recursive operation into subdirectories and -u to keep newer files at destination (=update). --progress shows progress information during operation. Jan 1 '17 at 16:59
  • I strongly suggest to add the -t option in order to keep the timestamp from the source
    – gluuke
    Nov 27 '20 at 10:35
8

You're not saying what shell you're using, so I'm going to assume ksh:

if [[ file1 -nt file2 ]]; then cp file1 file2; fi
2
  • Isn't bash most common?
    – Rob
    Sep 29 '11 at 16:58
  • 1
    @Rob, yes. This works in bash too, obviously. I just didn't have bash (or any standard Linux box) at hand when I wrote it. Sep 29 '11 at 23:12
4

yes|cp -ruv /from/* /to/.
yes - Answer yes to all the questions.
r - Recursive
u - update
v - Progress

works like xargs.

I don't know how to explain academically.

How to force cp to overwrite without confirmation

2
  • 1
    This is kind of cryptic. Can you expand your answer to be a little more explicit, maybe include an example? Thanks. from Review
    – fixer1234
    Nov 8 '16 at 18:03
  • yes -> Answer yes to all the questions. Nov 8 '16 at 18:34

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.