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!
You can do what you want with stat . stat -c%Y file will output the modification time of a file in seconds since Jan 1, 1970. date +%s will output the current time in seconds since Jan 1, 1970. Save this answer.
Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...
To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With