60

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.

4 Answers 4

76

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
  • 37
    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, 2016 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, 2020 at 9:49
30

Use rsync

rsync --progress -r -u /from/one/* /to/another/directory
3
  • 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.
    – JoeGo
    Jan 1, 2017 at 16:59
  • 2
    I strongly suggest to add the -t option in order to keep the timestamp from the source
    – gluuke
    Nov 27, 2020 at 10:35
  • 2
    i suggest also add -p to keep the same chmod and chown rsync --progress -rutp Jan 5, 2022 at 16:37
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, 2011 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, 2011 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, 2016 at 18:03
  • yes -> Answer yes to all the questions. Nov 8, 2016 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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