61

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.

random
  • 14,638
  • 9
  • 54
  • 58
Eli
  • 785
  • 2
  • 6
  • 7

4 Answers4

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/

Dennis
  • 6,578
  • 1
  • 28
  • 28
  • 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 '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 09:49
30

Use rsync

rsync --progress -r -u /from/one/* /to/another/directory
gnod
  • 433
  • 5
  • 6
  • 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 01 '17 at 16:59
  • 2
    I strongly suggest to add the `-t` option in order to keep the timestamp from the source – gluuke Nov 27 '20 at 10:35
  • 2
    i suggest also add -p to keep the same chmod and chown rsync --progress -rutp – Kamil Dąbrowski Jan 05 '22 at 16:37
9

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
Kusalananda
  • 2,333
  • 18
  • 24
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