5

I'm looking for a concise way to check if a file was copied using cp -u.

I have a little shell script which updates quite a number of files. At the moment the script echoes a little message for each file which gets copied.

Now I want to change the script in such a way that the echo only gets executed when the file actually was updated. I've checked if cp -u returned an error code if it didn't copy the file, but this isn't the case.

Is there a better way than manually comparing the timestamps of the files?

  • if cp -uv source destination; then echo copied; else echo not copied; fididn't work ? – Archemar Oct 9 '14 at 7:52
  • How come it didn't return a return code? jpkroehling@cupuacu ~ $ cp -u nginx.conf nginx.conf.copy jpkroehling@cupuacu ~ $ echo $? 0 jpkroehling@cupuacu ~ $ cp -u nginx.conf nginx.conf cp: ‘nginx.conf’ and ‘nginx.conf’ are the same file jpkroehling@cupuacu ~ $ echo $? 1 – jpkrohling Oct 9 '14 at 10:42
  • Ok, I give up in trying to get it printing nicely: pastebin.com/Bz4n8MVW – jpkrohling Oct 9 '14 at 10:43
  • 1
    It always returns 0, even if the file wasn't copied. At least on my system it does. – Sascha Wolf Oct 9 '14 at 10:43
  • 1
    @jpkrohling: in second case you tried to copied nginx.conf to nginx.conf and not to nginx.conf.copy. – Cyrus Oct 9 '14 at 14:59
7
if [ "$(cp -uv source destination)" != "" ]; then echo copied; else echo not copied; fi

Update

Match "->" in cp's verbose output. It only occurs if it could be successfully copied and if your filenames do not contain "->".

if [[ "$(cp -uv source destination)" =~ \-\> ]]; then echo copied; else echo not copied; fi
  • 1
    I'm kinda ashamed that I didn't thought of this. Thank you! – Sascha Wolf Oct 9 '14 at 7:46

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.