Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Linux Shell Scripting Cookbook

You're reading from   Linux Shell Scripting Cookbook Do amazing things with the shell and automate tedious tasks

Arrow left icon
Product type Paperback
Published in May 2017
Publisher
ISBN-13 9781785881985
Length 552 pages
Edition 3rd Edition
Tools
Arrow right icon
Authors (3):
Arrow left icon
Clif Flynt Clif Flynt
Author Profile Icon Clif Flynt
Clif Flynt
Sarath Lakshman Sarath Lakshman
Author Profile Icon Sarath Lakshman
Sarath Lakshman
Shantanu Tushar Shantanu Tushar
Author Profile Icon Shantanu Tushar
Shantanu Tushar
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Shell Something Out FREE CHAPTER 2. Have a Good Command 3. File In, File Out 4. Texting and Driving 5. Tangled Web? Not At All! 6. Repository Management 7. The Backup Plan 8. The Old-Boy Network 9. Put On the Monitors Cap 10. Administration Calls 11. Tracing the Clues 12. Tuning a Linux System 13. Containers, Virtual Machines, and the Cloud

Getting and setting dates and delays

A time delay is used to wait a set amount of time(such as 1 second) during the program execution, or to monitor a task every few seconds (or every few months). Working with times and dates requires an understanding of how time and date are represented and manipulated. This recipe will show you how to work with dates and time delays.

Getting ready

Dates can be printed in a variety of formats. Internally, dates are stored as an integer number of seconds since 00:00:00 1970-01-01. This is called epoch or Unix time.

The system's date can be set from the command line. The next recipes demonstrate how to read and set dates.

How to do it...

It is possible to read the dates in different formats and also to set the date.

  1. Read the date:
        $ date
        Thu May 20 23:09:04 IST 2010
  1. Print the epoch time:
        $ date +%s
        1290047248

The date command can convert many formatted date strings into the epoch time. This lets you use dates in multiple date formats as input. Usually, you don't need to bother about the date string format you use if you are collecting the date from a system log or any standard application generated output.
Convert the date string into epoch:

        $ date --date "Wed mar 15 08:09:16 EDT 2017" +%s
        1489579718

The --date option defines a date string as input. We can use any date formatting options to print the output. The date command can be used to find the day of the week given a date string:

        $ date --date "Jan 20 2001" +%A
        Saturday

The date format strings are listed in the table mentioned in the How it works... section

  1. Use a combination of format strings prefixed with + as an argument for the date command, to print the date in the format of your choice. Consider this example:
        $ date "+%d %B %Y"
        20 May 2010
  1. Set the date and time:                                                          
        # date -s "Formatted date string"
        # date -s "21 June 2009 11:01:22"
On a system connected to a network, you'll want to use ntpdate to set the date and time:
/usr/sbin/ntpdate -s time-b.nist.gov
  1. The rule for optimizing your code is to measure first. The date command can be used to time how long it takes a set of commands to execute:
        #!/bin/bash
        #Filename: time_take.sh
        start=$(date +%s)
        commands;
        statements;
        end=$(date +%s)
        difference=$(( end - start))
        echo Time taken to execute commands is $difference seconds.
The date command's minimum resolution is one second. A better method for timing commands is the time command:
time commandOrScriptName.

How it works...

The Unix epoch is defined as the number of seconds that have elapsed since midnight proleptic Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds. Epoch time is useful when you need to calculate the difference between two dates or times. Convert the two date strings to epoch and take the difference between the epoch values. This recipe calculates the number of seconds between two dates:

secs1=`date -d "Jan 2 1970" 
secs2=`date -d "Jan 3 1970" 
echo "There are `expr $secs2 - $secs1` seconds between Jan 2 and Jan 3" 
There are 86400 seconds between Jan 2 and Jan 3 

Displaying a time in seconds since midnight of January 1, 1970, is not easily read by humans. The date command supports output in human readable formats.

The following table lists the format options that the date command supports.

Date component
Format
Weekday

%a (for example, Sat)

%A (for example, Saturday)

Month

%b (for example, Nov)

%B (for example, November)

Day %d (for example, 31)
Date in format (mm/dd/yy) %D (for example, 10/18/10)
Year

%y (for example, 10)

%Y (for example, 2010)

Hour %I or %H (For example, 08)
Minute %M (for example, 33)
Second %S (for example, 10)
Nano second %N (for example, 695208515)
Epoch Unix time in seconds %s (for example, 1290049486)

There's more...

Producing time intervals is essential when writing monitoring scripts that execute in a loop. The following examples show how to generate time delays.

Producing delays in a script

The sleep command will delay a script's execution period of time given in seconds. The following script counts from 0 to 40 seconds using tput and sleep:

#!/bin/bash 
#Filename: sleep.sh 
echo Count: 
tput sc 

# Loop for 40 seconds 
for count in `seq 0 40` 
do 
  tput rc 
  tput ed 
  echo -n $count 
  sleep 1 
done

In the preceding example, a variable steps through the list of numbers generated by the seq command. We use tput sc to store the cursor position. On every loop execution, we write the new count in the terminal by restoring the cursor position using tput rc, and then clearing to the end of the line with tputs ed. After the line is cleared, the script echoes the new value. The sleep command causes the script to delay for 1 second between each iteration of the loop.

You have been reading a chapter from
Linux Shell Scripting Cookbook - Third Edition
Published in: May 2017
Publisher:
ISBN-13: 9781785881985
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime