Unix Scripting: Time and Date

If you have followed this blog for a while, you should remember how to use variables in Unix shell scripts.

Going further, I'd like to show you some basics of working with time and date in your scripts – generating all sorts of timestamps and timing some parts of your script for reporting purposes.

The history of (Unix) time

In case you didn't know, time in Unix starts with a Unix epoch, sometimes also referred to as POSIX epoch. The Unix epoch is the time 00:00:00 UTC on January 1, 1970.

Most of Unix-like system today store and calculate this time according to Unix epoch, which means they all have an internal counter which counts the number of seconds elapsed since midnight of January 1, 1970.

As you can imagine, this is a pretty big number (it passed 1,000,000,000 seconds back in 2001, just so that you know), and reporting in directly would not be very useful to real humans. Because of this, most of Unix time and date reporting commands and functions do the conversion from Unix time into something more meaningful to the end user.

While for the vast majority of time and date related tasks this conversion is good, a task of timing certain events can sometimes benefit from using raw second counters and simply subtracting them when needed.

Getting Unix time and date

In Unix shells, the easiest way to get a current time and date is to use the date command:

ubuntu$ date
Tue Jun 10 10:46:07 IST 2008

date is a very smart command, and apart from this default behavior it supports template system for printing the current time and date – so you can use it to report only specific part of the time and date like the current hour or the day of a week or the year.

Read the man page for date (type man date in your shell prompt) to learn all the details, but this is how you use date output templates:

ubuntu$ date "+%b %d, %Y"
Jun 10, 2008

In this example, the %b parameter in this template represents the short name of the current month, %d is the day of the month, and %Y is the four-digit representation of the current year.

Timing parts of your Unix script

If you're after timing some parts of your script, you'll need to use two variables: one for saving the time before the start of an observed part of the script, and another one for saving the time after the same piece of code.

These two variables will be used to subtract the time and report the elapsed time in seconds, so in order to do this we'll need the date command to report time in seconds. That's why I've given you an introduction to Unix time earlier: date reports the number of seconds since the Unix epoch:

ubuntu$ date +%s
1213091896

If you run it just a few seconds later, you'll see a different number:

ubuntu$ date +%s
1213091922

That's why, if such values are saved and then subtracted, we'll get the elapsed time in seconds.

Here's a simple script showing how this is done:

#!/bin/bash
#
START=`date +%s`
echo "Script start time (Unix epoch): $START"
#
echo "- sleeping for 3 seconds..."
sleep 3
echo "- sleeping for 2 seconds more..."
sleep 2
#
FINISH=`date +%s`
echo "Script finish time (Unix epoch): $FINISH"
#
ELAPSED=`expr $FINISH - $START`
echo "Elapsed time: $ELAPSED"

And if you run it, you will see this output:

ubuntu$ /tmp/time-example.sh
Script start time (Unix epoch): 1213092131
- sleeping for 3 seconds...
- sleeping for 2 seconds more...
Script finish time (Unix epoch): 1213092131
Elapsed time: 5

That's all I wanted to show you today. In future posts, I'll show you a few more things you can do regarding timing and timestamps in Unix. Until then – good luck with your scripting, and feel free to ask if you need any more help!

Related books

If you want to learn more, here's a great book:

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • http://www.unixguru.de UnixGuru

    Its interesting to see how the start and finish times in your script are identical. I could reproduce the same effect in my shell.

    however, the following code actually incrementy the unixtime in seconds:

    while (sleep 3; sleep 2)
    do
    date +%s
    done

    whereas your code doesnt. I find that strange.

    Has anybody got an explanation for this behavior of bash?

    Thanks,
    unixguru.

  • http://www.unixguru.de UnixGuru

    Oops.

    Thats no bash bug at all.

    Its a typo in line 12:
    12 echo "Script finish time (Unix epoch): $START"
    should be
    12 echo "Script finish time (Unix epoch): $FINISH"

    ;-)

  • Gleb Reys

    Good catch, thanks so much for pointing this out so quickly! Just fixed the original post, hope it won't confuse anyone else…

    I think the reason I didn't notice it was because the elapsed time was calculated correctly to be 5 seconds, so I didn't even question the rest of the output :)

    Thanks!

  • http://cactus-mouse.com Eugene Morozov

    Arithmetic expression could be written in a shorter and more readable way in bash:
    ELAPSED=$((FINISH - START))

  • Gleb Reys

    Thanks for the comment, Eugene!

    Yes, I was thinking of this form and find it easier to read as well, however I left it out because I haven't explained this bash expression evaluation syntax on my pages yet.

    Will do so this week!

  • Pingback: Unix scripts: basic arithmetic operations | UNIX Tutorial: Learn UNIX()

  • James

    am running process in a Unix box but need to know the time it will take to finish.
    can you help??

  • Gleb Reys

    Hi James,

    There's no easy way to confirm how long an already running process will take to complete, but I've just posted a quick entry about the time command.

    You can use it to run a command and it will then time exactly how long it took to complete the execution.

    If this isn't what you're looking for, please explain your situation and I'll see what else can be done.

    Thanks for stopping by and good luck!

  • Pingback: Parsing text files line by line in Unix script | UNIX Tutorial: Learn UNIX()

  • Pingback: Easy date calculations in Unix scripts with GNU date | UNIX Tutorial: Learn UNIX()

  • Pingback: Confirm the Day of the Week Based on a Timestamp | UNIX Tutorial: Learn UNIX()

  • Pingback: date - getting and setting current time and date in Unix | Unix Commands()

  • http://www.dward.us/ DaveQB

    Why not just use the 'time' command ?

    eg

    time dd if=/dev/zero of=test.img bs=512 count 30000

    ??

  • Gleb Reys

    Hi Dave,

    time command is a great tool when you need to measure the time for running a command or a whole script, your example is perfect.

    But what I'm explaining in this post is timing parts of the script, i.e. a certain execution path within the same script – and last time I checked you couldn't use time command as such a stopwatch.

    Thanks for stopping by! I'll update the post to make it include your example and explain my point a bit better.

  • http://www.gmail.com Abbadi

    Thanks for all ……

    BR,

  • http://www.gmail.com Abbadi

    Please can you tell me about any site that explains unix scripts for fresh programmer in unix

  • Gleb Reys

    Hi Abbadi, glad you liked the article! I post new links more or less every Tuesday, so if I come across such a site I'll definitely share it with everyone. I plan to cover a lot of basics myself, so feel free to submit your questions/topics.

  • Pingback: Converting date and time to Unix epoch in Perl | UNIX Tutorial: Learn UNIX()

  • prout

    Important! The typo is still here at line 12! Should read "$FINISH".

  • Azeem

    Great keep it up !!

  • bhenchood

    how to displa time and date using unix commandsss.. mother fuckrs

  • Pingback: Environment Variables in Unix | Unix Tutorial()

  • Date and time reset

    how the date and time automatically reset every 24 hours ? or 12 hours. In macosx

    Thanks

  • http://javarevisited.blogspot.sg/2012/03/10-example-of-chmod-command-in-unix.html Rajiv @ chmod command in unix

    Date is very powerful and can be used to convert time from one timezone to other, see here for 10 examples on date command in Unix

  • sarvaan

    $ date +%s
    %s

    it is printing the same %s ….?
    can you pls let me know,y it was printing this.