Linux Shell Scripting Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

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.