Handling dates in shell scripts

In shell scripts, sometimes it’s useful to act on events based on their timestamps. For example, let’s say you want to kill some type of process that has been running for longer than 5 hours in your system, or you want to check some remote API and act on the value of a timestamp in the response payload. When using rfc3339 it’s simple to handle that in bash.

Let’s take a look at the following function.

job_running_for_too_long() {
  export max_running_time="5 hours"
  export modified_date="2020-10-09T13:50:00Z"
  [ "$(date +%s)" -gt "$(date --date "${modified_date} +${max_running_time}" +%s)" ]

In this case, a job is defined as been running for too long if the time is past 2020-10-09T18:50:00Z.

When provided with the +%s flag the date command returns the number of seconds since 1970-01-01 00:00:00 in UTC. The number of seconds can then be used to perform arithmetic operations. In this case, we are checking if 5 hours have passed since 2020-10-09T13:50:00Z.

The above function was tested on Debian 10.

· shell