1

I have a file in which i have following content

2020-07-30 14:28:02|INFO|0||agent 1|CUpload|CUploadService 
2020-07-30 14:28:02|INFO|0||agent 1|CUpload|CUpload
2020-07-30 14:28:04|INFO|0||agent 1|CUpload|CUplo

I need to write a script through which i can calculate the time difference. If time is more than 60 minutes since the file updated last time, i need to write the column 3 in another file.

I am able to get the date in right format but i dont know how to take difference so it will tell me if it has been more than 60 mins or not.

date +%Y-%m-%d" "%H:%M:%S
2020-07-30 14:47:24

I have placed two times in a file and took their difference but it came out to be zero

more 3.unl | awk -F '|' '{print$2 - $1}'
Aserre
  • 4,916
  • 5
  • 33
  • 56
osia6028
  • 23
  • 6

1 Answers1

3

One possibility: convert date and time to epoch and subtract, eg:

#!/bin/bash

first='2020-07-30 14:28:04'
later='2020-07-30 15:39:09'

ep1=$(date --date="$first" +%s)
ep2=$(date --date="$later" +%s)

diff=$((ep2 - ep1))
echo diff $diff

if (( $diff > 3600 )); then
    echo actions ...
fi
Milag
  • 1,793
  • 2
  • 9
  • 8
  • `[[ $diff > 3600 ]]` should have been `(( $diff > 3600 ))` or `(( diff > 3600 ))` or `[[ $diff -gt 3600 ]]` – M. Nejat Aydin Jul 30 '20 at 12:42
  • right; reason: arithmetic instead of lexicographic; updated – Milag Jul 30 '20 at 12:52
  • Can also be done in fewer steps if you wanted. `(( (ep2-ep1) > 3600 ))` or even `(( ( $(date --date="$first" +%s) - $(date --date="$later" +%s) ) > 3600 ))` - but steps make it easier for most people to read and maintain. – Paul Hodges Jul 30 '20 at 13:09