Unix script to compare timestamp with current time

This is my first trip to the world of Unix scripting, and I'm not sure how to do it. I will query the DB and pull out the timestamp. I need to make this timestamp (in amazing format YYYYMMDDHHMMSS ), and if it is more than 10 minutes, return 1 else return 0.

Again, I have experience with this type of script (background in C ++ and C #), so if you guys don't mind a bit more explanation, I would be grateful - I also want to know how this works.

Thanks!

+4
source share
2 answers

Suppose $ dbtimestamp has a timestamp returned from the database, but I hardcode it here.

 dbtimestamp=20120306142400 secondsDiff=$(( `date '+%Y%m%d%H%M%S'` - $dbtimestamp )) if [ $secondsDiff -gt 600 ] then exit 1 else exit 0 fi 
+2
source

The way your tools work depends on the flavor of Unix that you use. The following should work on 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 MATH time. if [ $((now - epoch)) -gt 600 ]; then exit 1 fi exit 0 

Note that this value is /bin/sh script for portability, so it does not take advantage of bash -isms that you can get used to on Linux, in particular [[ ... ]] and heretext, to read variables.

Oh, and I suppose you meant "exit value" when you said "return value". The return value will be the result of the function, but what I wrote above is a stand-alone script.

Please note that this may not understand future timestamps, and does not take into account the time zone. If this is important to you, you should think about it. :-) And the test is in your environment.

+5
source

Source: https://habr.com/ru/post/1400067/


All Articles