Unix script to compare a timestamp with current time

shellunixunix-timestamp

This is my first journey into the realm of Unix scripting and I'm not sure how to go about this. Ill be querying a DB and pulling out a timestamp. What I need to do is take that timestamp (in the awesome format of YYYYMMDDHHMMSS) and if its more than 10 minutes old, return a 1 else return 0.

Again, I have essentially 0 experience with this type of scripting (background is in C++ and C#) so if you guys don't mind a little more explanation I'd be grateful – I want to learn how it works too.

Thanks!

Best Solution

The way your tools work depends on the flavour of Unix you use. The following should work in Linux, FreeBSD, NetBSD, OSX, etc.

#!/bin/sh

sample="${1:-20120306131701}"

if ! expr "$sample" : '[0-9]\{14\}$' >/dev/null; then
  echo "ERROR: unknown date format" >&2
  exit 65
fi

case $(uname -s) in
  *BSD|Darwin)
    # The BSD date command allows you to specify an input format.
    epoch=$(date -jf '%Y%m%d%H%M%S' "$sample" '+%s')
    ;;
  Linux)
    # No input format in Linux, so rewrite date to something '-d' will parse
    tmpdate="$(echo "$sample" | sed -r 's/(.{8})(..)(..)(..)/\1 \2:\3:\4/')"
    epoch=$(date -d "$tmpdate" '+%s')
    ;;
  *)
    echo "ERROR: I don't know how to do this in $(uname -s)." >&2
    exit 69
    ;;
esac

now=$(date '+%s')

# And with the provided datetime and current time as integers, it's MATH time.
if [ $((now - epoch)) -gt 600 ]; then
  exit 1
fi

exit 0

Note that this is a /bin/sh script, for the sake of portability, so it doesn't take advantage of bash-isms you may be used to in Linux, in particular [[ ... ]] and heretext to read variables.

Oh, and I'm assuming that you meant "exit value" when you said "return value". A return value would be the result of a function, but what I've written above is a stand-alone script.

Note that this may not understand timestamps in the future, nor does it take timezone into consideration. If that's important to you, you should, er, consider it. :-) And test in your environment.