Epoch Time shell script

Shell scripts

A shell script has a myriad of purposes on a Linux box. You can have them run at bootup so that they initiate commands or processes without you having to manually start them. They can be used to run a sequence of events. They can manipulate files, execute a program, print text, and walk your dog. Well, the last part is true if your dog is a robot. However, we're getting ahead of ourselves.

Epoch time, more commonly known as UNIX time (also POSIX time), is widely used in Linux (UNIX) systems as a way to describe instants in time. Specifically, it measures the number of seconds that have elapsed since January 1, 1970, and is used as a timestamp reference point.

With this shell script, we can quickly compare the Epoch time on our machine with the UTC that we are more accustomed to using.

How to do it...

Perform the following steps:

Unix time can be checked on most Unix systems by typing date +%s on the command line. Perform the following steps:

  1. First, create the following script in nano:
    $ sudo nano epoch-time.sh
    
  2. Then, paste the following code in the new window:
    # Epoch time in milliseconds
    # CTRL-C TO STOP
    # WRITTEN BY CHARLES HAMILTON
    # Simple script for showing the epoch time at 10-second intervals on a BeagleBone Black running Debian
    
    #!/bin/bash
    
    # Resets the RTC from  the system clock
    sudo hwclock --systohc
    sudo hwclock --show
    
    # Runs command for determining epoch time
    for (( ; ; ))
    do
            echo -n "Since Epoch [in milliseconds]: "
    # OPTION 1 command. Comment out if running OPTION 2.
            echo $(($(date +%s%N)/1000000))
    
    ## OPTION 2 command. Uncomment to run this version and comment out OPTION 1.
    #        cat /sys/class/rtc/rtc0/since_epoch | sed 's/...$//'
            sleep 10
    done

    Note

    If you run into problems while copying and pasting the code, download the script available at https://github.com/HudsonWerks/bash-script-samples/blob/master/epoch-time.sh.

  3. Now, run the following script:
    $ sudo bash epoch.sh
    
  4. Your screen output should look similar to this:
    Tue Oct 27 14:13:53 2015  -0.062322 seconds
    Since Epoch [in milliseconds]: 1445969632617
    Since Epoch [in milliseconds]: 1445969642630
    

    The script determines the Epoch time in milliseconds relative to the UTC time.

  5. Stop the script by pressing Ctrl + C.

There's more...

For some, all you can eat is buffets with shell scripts on the menu:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.239