Shell script to get the time difference
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:
#!/bin/bash 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
Output:
It took 4 seconds
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Other Helpful FAQs:
- Shell script error - bad interpreter messages and solution
- How to: Add or display today’s date from a shell script
- Howto run a shell script without changing file access permission
- Howto: Use mysql or run mysql queries from shell script
- What is the difference between UNIX and MAC OS X?
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: Bash, Linux, shell_script, sysadmin, time_difference_script, UNIX



May 8th, 2006 at 10:46 pm
What ifmy script takes mili seconds to execute and I want to be able to measure the time difference even if it is few micro seconds or mili seconds.
Thanks,
Ananda
August 22nd, 2006 at 7:35 pm
instead of
$(date +%s)
use
$(date +%s%N)
and you will get nanoseconds precision
—
Mitsuhashi Da! Oboeteoke!
March 25th, 2007 at 8:22 am
i need to find the no.of days between system date and the date of file creation. how do i achieve this?
August 16th, 2007 at 9:11 am
i need to find the no.of days and time between system date and the date of file creation. how do i achieve this?
September 12th, 2007 at 12:14 pm
Hi, you time diff script doesn’t work. date +%s returns only %s as value. And thus it does not work forward.
September 14th, 2007 at 12:45 pm
The above mentioned script will not work because “%s” is given in small letter.
Replace “%s” with “%S” and the script will work.
October 23rd, 2007 at 8:59 am
can i have the similar script in k-shell
May 8th, 2008 at 1:24 pm
Cool script, thanks!