I am trying to calculate the time elapsed since the log file was last updated.

I guess following commands will be used

lastUpdate=$(date -r myLogFile.log)

How can I subtract them and get result for number of seconds elapsed?

  • 2
    Use +%s (seconds from EPOC) of date output formatting option. – Costas Mar 3 '15 at 18:55
  • you meant lastUpdate=$(date -r myLogFile.log +%s)??? i m not able to get the difference stored in variable and i am new to Shell scripting... – Tarik Setia Mar 3 '15 at 19:32
lastUpdate="$(stat -c %Y myLogFile.log)"
now="$(date +%s)"
let diff="${now}-${lastUpdate}"

compare the two outputs to get the number of seconds between now and the modified date

stat -c %Y file  vs date +%s

One liner:

stat -c %Y /path/to/file | echo `expr $(date +%s) - $(cat)`

  • gives me "cat: -: input/output error expr: syntaxerror" – user640916 Dec 1 '17 at 2:03

You're almost there! Just tell date to use a format on which computation is easy.

lastUpdate=$(date -r myLogFile.log +%s)
now=$(date +%s)
file_age=$((now - lastUpdate))

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.