Bash – How to measure how long it takes the script to run AND include that in an email it generates

bashshell-scripttime

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?

Best Answer

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.