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 (ping, 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?

Asked By: Mike B

||

I suggest to take a look at bash variable SECONDS:

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.

Answered By: jimmij

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 bash specific.

Answered By: Steve Wills

While using SECONDS and 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.

Answered By: rahul

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.

Reply-To: someone@somehost
Sender: someone <someone@somehost>
To: somebody@somewhere.else
Subject: some subject
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
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 somebody@somewhere.else

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.

Answered By: mckenzm
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.