0

How to use cp -u to only copy if content is different, it fails when doing as below

$ cd /tmp/exper ; cp -v ~/Downloads/C/test.c . ; sudo chmod -R 777 . 
/home/budi/Downloads/C/test.c -> 'test.c'
$ cp -v -u test.c ~/Downloads/C
'test.c' -> '/home/budi/Downloads/C/test.c

as content is the same but through sudo chmod -R 777 .

How to do this correctly?

2
  • 1
    I have no idea what this code block is trying to show - I can hardly tell apart prompt and command.. Please edit your question and be more verbose. Commented Jun 14, 2022 at 14:35
  • 1
    I suggest that you start using rsync instead of cp. rsync has a lot more features, it is well described in the manual, and you can easily get help here or read tutorials via the internet. Please notice that rsync is not only targeting remote copying of files, it works well locally between different locations in a computer. Commented Jun 14, 2022 at 18:08

2 Answers 2

0
cd /tmp/exper ; cp -v ~/Downloads/C/test.c .

cp -u doesn't check for content, at all!

It checks for date of last modification. Only if the source file (~/Downloads/C/test.c) is newer than the target file (/tmp/exper/test.c), the copy will be made.

(by the way, the commands you show do not match the output you've pasted. And it's not celar what the sudo chmod -R 777 . is doing there.)

But there's nothing wrong here: The fact that cp prints sourcefile -> targetfile does not mean that the file has been copied, only that it has been considered for copying.

0

As pointed out by @MarcusMüller, cp -u checks file modification date, not content and only copies when the source is newer than the target or when the target does not exists.

The fact you get 'A' -> 'foobar/A' when you do \cp -uv A foobar/ shows that the copy did take place. This is the normal behavior on Debian family systems and I suspect on most other Linux flavors (although BSD and OSX may behave differently). So why do you get this result ?

Simply because when you do \cp -uv A foobar/, the newly created or copied foobar/A is more recent than A. So when you decide to do the reverse copy operation, i.e. \cp -uv foobar/A . the copy takes place quite normally.

You must log in to answer this question.