Book Image

Linux Shell Scripting Cookbook - Third Edition

By : Clif Flynt, Sarath Lakshman, Shantanu Tushar
Book Image

Linux Shell Scripting Cookbook - Third Edition

By: Clif Flynt, Sarath Lakshman, Shantanu Tushar

Overview of this book

The shell is the most powerful tool your computer provides. Despite having it at their fingertips, many users are unaware of how much the shell can accomplish. Using the shell, you can generate databases and web pages from sets of files, automate monotonous admin tasks such as system backups, monitor your system's health and activity, identify network bottlenecks and system resource hogs, and more. This book will show you how to do all this and much more. This book, now in its third edition, describes the exciting new features in the newest Linux distributions to help you accomplish more than you imagine. It shows how to use simple commands to automate complex tasks, automate web interactions, download videos, set up containers and cloud servers, and even get free SSL certificates. Starting with the basics of the shell, you will learn simple commands and how to apply them to real-world issues. From there, you'll learn text processing, web interactions, network and system monitoring, and system tuning. Software engineers will learn how to examine system applications, how to use modern software management tools such as git and fossil for their own work, and how to submit patches to open-source projects. Finally, you'll learn how to set up Linux Containers and Virtual machines and even run your own Cloud server with a free SSL Certificate from letsencrypt.org.
Table of Contents (14 chapters)

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.