7

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)
now=$(date)

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

2
  • 2
    Use +%s (seconds from EPOC) of date output formatting option. Commented Mar 3, 2015 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... Commented Mar 3, 2015 at 19:32

4 Answers 4

5
lastUpdate="$(stat -c %Y myLogFile.log)"
now="$(date +%s)"
let diff="${now}-${lastUpdate}"
0
3

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

stat -c %Y file  vs date +%s
2

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))
2

One liner:

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

1
  • gives me "cat: -: input/output error expr: syntaxerror" Commented Dec 1, 2017 at 2:03

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.