Shell script to get the time difference

Posted on in Categories , , , , last updated September 19, 2007

Q. I am able to write PHP or Perl script where I can find out time difference between script executions. Now I have .shtml file that is nothing but a shell script outputting some data to browser. What I want is time difference or time it took to execute a script. How do I write a shell script?

A. Your Logic should be as follows:

* Get start time and store to a variable START

* Execute a shell script

* Grab output and send to web browser

* Get time again and store to a variable END

* Calculate difference using expression END – START

Shell script o get the time difference

Here is small script that does the same thing (please note that script teated on GNU/Linux and with GNU date command only):
$ vi timediff.bash
Append text as follows:

START=$(date +%s)
# do something

# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here

END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"

Save and execute the script as follows:
$ chmod +x timediff.bash
Execute the script:
$ ./timediff.bash

It took 4 seconds