Copying a file only when it is newer than the destination

39

5

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.

Eli

Posted 2011-09-29T15:22:23.550

Reputation: 545

Answers

57

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

Posted 2011-09-29T15:22:23.550

Reputation: 5 768

21To 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 – 2016-10-21T13:04:20.347

20

Use rsync

rsync --progress -r -u /from/one/* /to/another/directory

gnod

Posted 2011-09-29T15:22:23.550

Reputation: 333

3Just 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 – 2017-01-01T16:59:35.913

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

Kusalananda

Posted 2011-09-29T15:22:23.550

Reputation: 1 941

Isn't bash most common? – Rob – 2011-09-29T16:58:52.727

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 – 2011-09-29T23:12:01.820

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

Felippe Silvestre

Posted 2011-09-29T15:22:23.550

Reputation: 49

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 – 2016-11-08T18:03:56.093

yes -> Answer yes to all the questions. – Felippe Silvestre – 2016-11-08T18:34:35.300