I have two time variables in bash. I am trying to find a way to get the time difference between the two.

Yes, I have read many many many examples on the net, but they do not seem to have a "simple" solution. Rather, it seems as if time arithmetic in Bash was an "afterthought".

Here are some of the links I have read: Link 1

Link 2

Link 3

It would appear as if there is no "elegant" solution for it (my opinion).

So my variables are like the following:

    TIME_START="date +%H:%M:%S //Start of script
    // The script
    TIME_END="date +%H:%M:%S //End of script

So I am trying to get the elapsed time. The script can take up to 3 hours to execute (interacting with sensors and hardware etc.). The TIME_START variable gets inserted into MySQL and later retrieved by Bash (when the script ends) in order to do the "elapsed time" calculation.

I have read somewhere that the following code would work, but it did not:

   diff=$(expr $TIME_END - $TIME_START)
   echo $diff

Any ideas?

Thank you


  • Please fix the syntax in the code you posted. The quotes are not closed and you seem to use C++ style comments. If this executed in bash you will most likely see error messages.
    – Lucas
    Feb 1, 2017 at 13:36
  • By the way, all arithmetic in bash (and other shells) is an "afterthought" and there is nothing elegant about shell scripting. It isn't a proper scripting language, and it isn't trying to be. The shell is for simple strings of commands cobbled together with primitive control structures. If you want elegant, or arithmetic, or pretty much anything sophisticated, you don't use shell scripts.
    – terdon
    Feb 1, 2017 at 16:01

2 Answers 2


Apart from calculating the duration of your script yourself (preferably with the values returned from date +%s as Roman has pointed out) you have some other options.

There is a command called time. You can execute time some-script.sh and it will print the time the script took to run at the end. See the man page.

You can also use $SECONDS in your bash script. It will hold the number of seconds since the process started. So you can echo It took $SECONDS at the end of your script or so. Search for $SECONDS in the bash man page.

And there also is the times builtin in bash. It prints information similar to time but for the shell itself (the process that executes it) not any command it is handed (it actually takes no arguments). Again see man bash.

EDIT: Your second link actually provides a solution that looks very similar to what you try and it also uses the +%s format string Roman mentioned.

  • I'll use the "seconds" option. Thank you for your time ...
    – Danny
    Feb 1, 2017 at 14:30

You can use date +%s -- it store seconds since 1970-01-01 00:00:00 UTC

Not the answer you're looking for? Browse other questions tagged .