3

I am looking for a simple bash solution to perform an action when a file is updated after a command like wget --timestamp https://example.com/my.file

I observed that wget returns 0 on both case, when the files is already latest version and also when it did download a newer one.

What's the easiest way to implement this in bash?

sorin
  • 161,544
  • 178
  • 535
  • 806
  • 2
    Save as a different file then compare them, if they are different then do whatever –  Feb 09 '15 at 10:43
  • 2
    @JID I would rather save the datetime of the file in a variable before running wget and checking it after the execution. I don't want to add new files to the disk for no good reason. – sorin Feb 09 '15 at 11:47
  • 2
    I wouldn't say it is for no good reason as it solves your problem. Depending on the size of the file, it would probably be on the disk for less than a few seconds. You could also use `-qO-` and compare the stdout that this produces against the original.Or you could save the datetime into a variable as you have said, although i don't know what the point of the question is in that case. –  Feb 09 '15 at 11:54
  • 3
    If the remote file supports HTTP HEAD, use `curl -I https://example.com/my.file` and compare the timestamp on your local file with the `Last-Modified` header value of the remote file – arco444 Feb 09 '15 at 12:00
  • 1
    You can use `inotifywait` to check for file changes. – l0b0 Feb 09 '15 at 12:57
  • Can you check if my answer is correct? – Ortomala Lokni May 13 '15 at 15:18

1 Answers1

4

You can use stat -c %y to save the timestamp of the last data modification, before and after the execution of wget. Then run your action if the two timestamps are different.

t1=$(stat -c %y $FILE)
wget https://example.com/$FILE
t2=$(stat -c %y $FILE)
if [ "$t1" != "$t2" ]; then
   echo "Do something"
fi

If you are using a BSD-like Unix such as macos use stat -f %m instead of stat -c %y.

Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
  • Great workarround... Side note: This will produce `[: too many arguments` error. (stat timestamp has spaces). Use double square brackets or double quotes... See http://stackoverflow.com/a/13781217/1601332 – gmo Feb 14 '17 at 11:52
  • 1
    Thanks for your remark, I've modified my answer accordingly. – Ortomala Lokni Feb 14 '17 at 15:15