How can measure how long it takes my script to run AND include that in an email it generates?
I have a simple bash script that runs a series of checks (
nslookup, etc) and then sends an email report with the output of that data.
I’d like the email to include information on how long it took the entire script to run. Is there an easy way to collect that information?
I suggest to take a look at
SECONDS: Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned.
Thus you can simply print this variable at the end of the script. Alternatively, if your intention is to measure the time of only part of the program, then just set
SECONDS=0 at the beginning of the measured block of commands, and at the end just use value stored in this variable.
Prefix your command with
/usr/bin/time and the time command will output the time it took the script to run. This is more portable than the using something
time will give you relative values. If you’d like to have absolute values for Auditing and Reporting Purposes as to when the script ran and when it completed, you might want to try something like this before and after your commands
date '+%Y%m%d%H%M%S.%N' . This could also give you a better granularity as it can capture sub-second differences as you have commands like
ping which normally execute within a second.
Nest your script.
To send an email there are a number of options. I personally favour msmtp for this, you can define the headers yourself “here” style (inline) or use a separate file and cat them together. There are all sorts of alternatives to this involving perl, python etc.
Sender: someone <someone@somehost>
Subject: some subject
Content-Type: text/html; charset="iso-8859-1"
The trailing blank line is important.
cat your assembled message into msmtp thusly :
cat assembled.eml | msmtp firstname.lastname@example.org
A pessimist would loop until success a reasonable number of times.
The payload could also be html, and could be php generated.
A very ugly alternative for “batchy” operation overnight say is to create a cronjob and the output is emailed in lieu of stdout/stderr.