44

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.

63

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

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

| improve this answer | |
  • 26
    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 at 9:49
23

Use rsync

rsync --progress -r -u /from/one/* /to/another/directory
| improve this answer | |
  • 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. – Jörg Gottschlich Jan 1 '17 at 16:59
6

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
| improve this answer | |
  • 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. – Kusalananda 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

| improve this answer | |
  • 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. – Felippe Silvestre 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.