Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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, Second Edition

You're reading from   Linux Shell Scripting Cookbook, Second Edition Don't neglect the shell ‚Äì this book will empower you to use simple commands to perform complex tasks. Whether you're a casual or advanced Linux user, the cookbook approach makes it all so brilliantly accessible and, above all, useful.

Arrow left icon
Product type Paperback
Published in May 2013
Publisher Packt
ISBN-13 9781782162742
Length 384 pages
Edition 2nd Edition
Tools
Arrow right icon
Toc

Table of Contents (16) Chapters Close

Linux Shell Scripting Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
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. The Backup Plan 7. The Old-boy Network 8. Put on the Monitor's Cap 9. Administration Calls Index

Getting and setting dates and delays


Many applications require printing dates in different formats, setting date and time, and performing manipulations based on date and time. Delays are commonly used to provide a wait time (such as 1 second) during the program execution. Scripting contexts, such as monitoring a task every 5 seconds, demands the understanding of writing delays in a program. This recipe will show you how to work with dates and time delays.

Getting ready

Dates can be printed in variety of formats. We can also set dates from the command line. In Unix-like systems, dates are stored as an integer, which denotes the number of seconds since 1970-01-01 00:00:00 UTC. This is called epoch or Unix time . Let us see how to read dates and set them.

How to do it...

It is possible to read the dates in different formats and also to set the date. This can be accomplished with these steps:

  1. You can read the date as follows:

    $ date
    Thu May 20 23:09:04 IST 2010
    
  2. The epoch time can be printed as follows:

    $ date +%s
    1290047248
    

    We can find out epoch from a given formatted date string. You can use dates in multiple date formats as input. Usually, you don't need to bother about the date string format that you use if you are collecting the date from a system log or any standard application generated output. Convert the date string into epoch as follows:

    $ date --date "Thu Nov 18 08:07:21 IST 2010" +%s
    1290047841
    

    The --date option is used to provide a date string as input. However, we can use any date formatting options to print the output. Feeding the input date from a string can be used to find out the weekday, given the date.

    For example:

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

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

  3. 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. For example:

    $ date "+%d %B %Y"
    20 May 2010
    
  4. We can set the date and time as follows:

    # date -s "Formatted date string"
    

    For example:

    # date -s "21 June 2009 11:01:22"
    
  5. Sometimes we need to check the time taken by a set of commands. We can display it using the following code:

    #!/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.

Note

An alternate method would be to use time <scriptpath> to get the time that it took to execute the script.

How it works...

While considering dates and time, 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 very useful when you need to calculate the difference between two dates or time. You may find out the epoch times for two given timestamps and take the difference between the epoch values. Therefore, you can find out the total number of seconds between two dates.

To write a date format to get the output as required, use the following table:

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 very essential when writing monitoring scripts that execute in a loop. Let us see how to generate time delays.

Producing delays in a script

To delay execution in a script for a particular period of time, use sleep:$ sleepno_of_seconds. For example, the following script counts from 0 to 40 by using tput and sleep:

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

count=0;
while true;
do
    if [ $count -lt 40 ];
    then
        let count++;
        sleep 1;
        tput rc
        tput ed
        echo -n $count;
    else exit 0;
    fi
done

In the preceding example, a variable count is initialized to 0 and is incremented on every loop execution. The echo statement prints the text. 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 for the number. The cursor position is restored using tput rc. This clears text from the current cursor position to the end of the line, so that the older number can be cleared and the count can be written. A delay of 1 second is provided in the loop by using the sleep command.

You have been reading a chapter from
Linux Shell Scripting Cookbook, Second Edition - Second Edition
Published in: May 2013
Publisher: Packt
ISBN-13: 9781782162742
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