Bash on the date and time operations used a custom function

In the preparation of Linux Bash script, often using some date and time the command, the following is commonly used in my many years Shell programming function, now sorted out, I hope, serve.

Annex consists of three files:

datetime.sh includes Bash in operation on the date and time the common custom function

test_datetime.sh to demonstrate datetime.sh the use of custom functions

test_datetime.txt is an implementation of the output sample test_datetime.sh

Execute the command:

./test_datetime.sh >test_datetime.txt

File: datetime.sh

#!/bin/sh

# Copyright (c) 2010 codingstandards. All rights reserved.
# file: datetime.sh
# description: Bash In about date-time common custom function
# license: LGPL
# author: codingstandards
# email: codingstandards@gmail.com
# version: 1.0
# date: 2010.02.27

# usage: yesterday
#  Yesterday
#  For example, today is the 2010  2 On 27 January  , The result is  2010-02-26
yesterday()
{
        date --date='1 day ago' +%Y-%m-%d
}

# usage: today
#  Today
#  For example, today is the 2010  2 On 27 January  , The result is  2010-02-27
today()
{
        date +%Y-%m-%d
}

# usage: now
#  Now, including date and time  . Nanosecond
#  For example,  :2010-02-27 11:29:52.991774000
now()
{
    date "+%Y-%m-%d %H:%M:%S.%N"
}

# usage: curtime
#  The current time, including date and time
#  For example,  :2010-02-27 11:51:04
curtime()
{
        date '+%Y-%m-%d %H:%M:%S'
        #  Can also be written as  :date '+%F %T'
}

# usage: last_month
#  For the last month of the year
#  For example,  :2010-01
last_month()
{
        date --date='1 month ago' '+%Y-%m'
}

# usage: last_month_packed
#  For the last month of the year
#  For example,  :201001
last_month_packed()
{
        date --date='1 month ago' '+%Y%m'
}

# usage: first_date_of_last_month
#  From last month's first day
#  For example, this month is 2010  2 Month, then the result is  2010-01-01
first_date_of_last_month()
{
        date --date='1 month ago' '+%Y-%m-01'
}

# usage: last_date_of_last_month
#  From last month's last day
#  For example, is currently the 2010  2 Month, then the result is  2010-01-31
last_date_of_last_month()
{
        date --date="$(date +%e) days ago" '+%Y-%m-%d'
}

# usage: day_of_week
#  Today's week
# day of week (0..6);  0 represents Sunday
day_of_week()
{
        date +%w
}

# usage: last_hour
#  Last hour
#  For example,  :2010-02-27-10
#  For log4j generated log file name
last_hour()
{
        date --date='1 hour ago' +%Y-%m-%d-%H
}

# usage: the_hour
#  The current hour, for the convenience of arithmetic comparison  , The result does not start at 0
#  For example,  :12
the_hour()
{
        #date +%H       # hour (00..23)
        date +%k        # hour ( 0..23)
}

# usage: the_minute
#  The current minute, for the convenience of arithmetic comparison  , The result does not start at 0
#  For example,  :
the_minute()
{
        MM=$(date +%M)  # minute (00..59)
        echo $[1$MM-100]
}

# usage: the_second
#  The current number of seconds
#  For example,  :
the_second()
{
        SS=$(date +%S)  # second (00..60); the 60 is necessary to accommodate a leap  second
        echo $[1$SS-100]
}

# usage: the_year
#  The current year   year (1970...)
#  For example,  :2010
the_year()
{
        date +%Y
}

# usage: the_month
#  The current month, for the convenience of an arithmetic comparison  , The result does not start at 0
#  For example,  :2
the_month()
{
        M=$(date +%m) # month (01..12)
        echo $[1$M-100]
}

# usage: the_date
#  The current date, in order to facilitate the arithmetic comparison  , The result does not start at 0
#  For example,  :27
the_date()
{
        date +%e        # day of month, blank padded ( 1..31)
}

# usage: days_ago <n>
#  Take n days before the date of
#  For example,  :days_ago 0 Today, days_ago 1 it was yesterday  ,days_ago 2 It is the day before yesterday, days_ago-1 is tomorrow
#  Format  :2010-02-27
days_ago()
{
        date --date="$1 days ago" +%Y-%m-%d
}

# usage: chinese_date_and_week()
#  Print Chinese date and week
#  For example,  :2 On 27 January    Saturday
chinese_date_and_week()
{
        WEEKDAYS=( Sunday Monday    Tuesday and Wednesday    Thursday Friday    Saturday  )
        WEEKDAY=$(date +%w)
        #DT="$(date +%Y Year  %m Month  %d Day  ) ${WEEKDAYS[$WEEKDAY]}"
        MN=1$(date +%m)
        MN=$[MN-100]
        DN=1$(date +%d)
        DN=$[DN-100]
        DT="$MN Month  $DN Day   ${WEEKDAYS[$WEEKDAY]}"
        echo "$DT"
}

# usage: rand_digit
#  Random numbers  ,0-9
rand_digit()
{
    S="$(date +%N)"
    echo "${S:5:1}"
}

# usage: seconds_of_date [<date> [<time>]]
#  Gets the number of seconds specified date  ( Since 1970  )
#  For example,  :seconds_of_date "2010-02-27"  Returns the   1267200000
seconds_of_date()
{
        if [ "$1" ]; then
                date -d "$1 $2" +%s
        else
                date +%s
        fi
}

# usage: date_of_seconds <seconds>
#  According to the number of seconds  ( Since 1970  ) Get the date
#  For example,  :date_of_seconds 1267200000  Returns the   2010-02-27
date_of_seconds()
{
        date -d "1970-01-01 UTC $1 seconds" "+%Y-%m-%d"
}

# usage: datetime_of_seconds <seconds>
#  According to the number of seconds  ( Since 1970  ) Get the date-time
#  For example,  :datetime_of_seconds 1267257201  Returns the   2010-02-27 15:53:21
datetime_of_seconds()
{
        date -d "1970-01-01 UTC $1 seconds" "+%Y-%m-%d %H:%M:%S"
}

# usage: leap_year <yyyy>
#  In determining whether a leap year
#  If yyyy is a leap year  , Exit code  0: Otherwise non-  0
#  Typical examples are as follows  :
# if leap_year 2010; then
#       echo "2010 is leap year";
# fi
# if leap_year 2008; then
#       echo "2008 is leap year";
# fi
#  Excerpt from script  :datetime_util.sh (2007.06.11)
#  Note  : This script comes from network, slightly modified  ( The original script from standard input Gets a year, has now changed to the specified by the parameter  )
# Shell program to read any year and find whether leap year or not
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
leap_year()
{
        # store year
        yy=$1
        isleap="false"

        #echo -n "Enter year (yyyy) : "
        #read yy

        # find out if it is a leap year or not

        if [ $((yy % 4)) -ne 0 ] ; then
                : #  not a leap year : means do nothing and use old value of isleap
        elif [ $((yy % 400)) -eq 0 ] ; then
                # yes, it's a leap year
                isleap="true"
        elif [ $((yy % 100)) -eq 0 ] ; then
                : # not a leap year do nothing and use old value of isleap
        else
                # it is a leap year
                isleap="true"
        fi
        #echo $isleap
        if [ "$isleap" == "true" ]; then
                #  echo "$yy is leap year"
                return 0
        else
                #  echo "$yy is NOT leap year"
                return 1
        fi
}

# usage: validity_of_date <yyyy> <mm> <dd>
#  To determine the lawfulness of date yyyy-mm-dd
#  If is, the exit code for the  0: Otherwise non-  0
#  Typical examples are as follows  :
# if validity_of_date 2007 02 03; then
#       echo "2007 02 03 is valid date"
# fi
# if validity_of_date 2007 02 28; then
#       echo "2007 02 28 is valid date"
# fi
# if validity_of_date 2007 02 29; then
#       echo "2007 02 29 is valid date"
# fi
# if validity_of_date 2007 03 00; then
#       echo "2007 03 00 is valid date"
# fi
#  Excerpt from script  :datetime_util.sh (2007.06.11)
#  Note  : This script comes from network, slightly modified  ( The original script from standard input for year, month, instead of by parameter specifies  )
# Shell program to find the validity of a given date
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
validity_of_date()
{
        # store day, month and year
        yy=$1
        mm=$2
        dd=$3

        # store number of days in a month
        days=0

        # get day, month and year
        #echo -n "Enter day (dd) : "
        #read dd

        #echo -n "Enter month (mm) : "
        #read mm

        #echo -n "Enter year (yyyy) : "
        #read yy

        # if month is negative (<0) or greater than 12
        # then it is invalid month
        if [ $mm -le 0 -o $mm -gt 12 ]; then
                #echo "$mm is invalid month."
                return 1
        fi

        # Find out number of days in given month
        case $mm in
                1) days=31;;
                01) days=31;;
                2) days=28 ;;
                02) days=28 ;;
                3) days=31 ;;
                03) days=31 ;;
                4) days=30 ;;
                04) days=30 ;;
                5) days=31 ;;
                05) days=31 ;;
                6) days=30 ;;
                06) days=30 ;;
                7) days=31 ;;
                07) days=31 ;;
                8) days=31 ;;
                08) days=31 ;;
                9) days=30 ;;
                09) days=30 ;;
                10) days=31 ;;
                11) days=30 ;;
                12) days=31 ;;
                *) days=-1;;
        esac

        # find out if it is a leap year or not

        if [ $mm -eq 2 ]; then # if it is feb month then only check of leap year
                if [ $((yy % 4)) -ne 0 ] ; then
                        : #  not a leap year : means do nothing and use old value of days
                elif [ $((yy % 400)) -eq 0 ] ; then
                        # yes, it's a leap year
                        days=29
                elif [ $((yy % 100)) -eq 0 ] ; then
                        : # not a leap year do nothing and use old value of days
                else
                        # it is a leap year
                        days=29
                fi
        fi

        #echo $days

        # if day is negative (<0) and if day is more than
        # that months days then day is invaild
        if [ $dd -le 0 -o $dd -gt $days ]; then
                #echo "$dd day is invalid"
                return 3
        fi

        # if no error that means date dd/mm/yyyy is valid one
        #echo "$dd/$mm/$yy is a vaild date"
        #echo "$yy-$mm-$dd is a valid date"
        #echo "valid"
        return 0
}

# usage: days_of_month <mm> <yyyy>
#  Gets the yyyy  mm The number of days in the month, pay attention to the order of parameters
#  For example,  :days_of_month 2 2007  The result is  28
days_of_month()
{
        # store day, month and year
        mm=$1
        yy=$2

        # store number of days in a month
        days=0

        # get day, month and year
        #echo -n "Enter day (dd) : "
        #read dd

        #echo -n "Enter month (mm) : "
        #read mm

        #echo -n "Enter year (yyyy) : "
        #read yy

        # if month is negative (<0) or greater than 12
        # then it is invalid month
        if [ $mm -le 0 -o $mm -gt 12 ]; then
                #echo "$mm is invalid month."
                echo -1
                return 1
        fi

        # Find out number of days in given month
        case $mm in
                1) days=31;;
                01) days=31;;
                2) days=28 ;;
                02) days=28 ;;
                3) days=31 ;;
                03) days=31 ;;
                4) days=30 ;;
                04) days=30 ;;
                5) days=31 ;;
                05) days=31 ;;
                6) days=30 ;;
                06) days=30 ;;
                7) days=31 ;;
                07) days=31 ;;
                8) days=31 ;;
                08) days=31 ;;
                9) days=30 ;;
                09) days=30 ;;
                10) days=31 ;;
                11) days=30 ;;
                12) days=31 ;;
                *) days=-1;;
        esac

        # find out if it is a leap year or not

        if [ $mm -eq 2 ]; then # if it is feb month then only check of leap year
                if [ $((yy % 4)) -ne 0 ] ; then
                        : #  not a leap year : means do nothing and use old value of days
                elif [ $((yy % 400)) -eq 0 ] ; then
                        # yes, it's a leap year
                        days=29
                elif [ $((yy % 100)) -eq 0 ] ; then
                        : # not a leap year do nothing and use old value of days
                else
                        # it is a leap year
                        days=29
                fi
        fi

        echo $days
}

File: test_datetime.sh

#!/bin/sh

# TODO:  Note that depending on the actual location change datetime.sh
. /opt/shtools/commons/datetime.sh

echo " The current time  (date):$(date)"
echo " Yesterday  (yesterday):$(yesterday)"
echo " Today  (today):$(today)"
echo " Now  (now):$(now)"
echo " Now  (curtime):$(curtime)"
echo " Last month  (last_month):$(last_month)"
echo " Last month  (last_month_packed):$(last_month_packed)"
echo " The first day of the last month  (first_date_of_last_month):$(first_date_of_last_month)"
echo " Last month, the last day  (last_date_of_last_month):$(last_date_of_last_month)"
echo " Today the day of the week  (day_of_week):$(day_of_week)"
echo " Last hour  (last_hour):$(last_hour)"
echo " The current hour  (the_hour):$(the_hour)"
echo " The current minutes  (the_minute):$(the_minute)"
echo " The current seconds  (the_second):$(the_second)"
echo " The current year  (the_year):$(the_year)"
echo " The current month  (the_month):$(the_month)"
echo " Current date  (the_date):$(the_date)"
echo " The day before yesterday  (days_ago 2):$(days_ago 2)"
echo " Tomorrow  (days_ago -1):$(days_ago -1)"
echo " The day after tomorrow  (days_ago -2):$(days_ago -2)"
echo " Ten days before the date of  (days_ago 10):$(days_ago 10)"
echo " Chinese date weeks  (chinese_date_and_week):$(chinese_date_and_week)"
echo " Random numbers  (rand_digit):$(rand_digit)"
echo " Random numbers  (rand_digit):$(rand_digit)"
echo " Since 1970 the number of seconds to  (seconds_of_date):$(seconds_of_date)"
echo " Since 1970 the number of seconds to  (seconds_of_date 2010-02-27):$(seconds_of_date 2010-02-27)"
echo " Since 1970 the number of seconds to  (seconds_of_date 2010-02-27 15:53:21):$(seconds_of_date 2010-02-27 15:53:21)"
echo " Since 1970 the number of seconds to the corresponding date  (date_of_seconds 1267200000):$(date_of_seconds 1267200000)"
echo " Since 1970 the number of seconds to the corresponding date time  (datetime_of_seconds 1267257201):$(datetime_of_seconds 1267257201)"

if leap_year 2010; then
        echo "2010 Year is a leap year  ";
fi
if leap_year 2008; then
        echo "2008 Year is a leap year  ";
fi
if validity_of_date 2007 02 03; then
        echo "2007 02 03  Date legitimate  "
fi
if validity_of_date 2007 02 28; then
        echo "2007 02 28  Date legitimate  "
fi
if validity_of_date 2007 02 29; then
        echo "2007 02 29  Date legitimate  "
fi
if validity_of_date 2007 03 00; then
        echo "2007 03 00  Date legitimate  "
fi

echo "2010 The number of days in February  (days_of_month 2 2010):$(days_of_month 2 2010)"
echo "2008 The number of days in February  (days_of_month 2 2008):$(days_of_month 2 2008)"

File: test_datetime.txt

 The current time  (date): February 6   27 15:58:28 CST 2010
 Yesterday  (yesterday):2010-02-26
 Today  (today):2010-02-27
 Now  (now):2010-02-27 15:58:28.734817000
 Now  (curtime):2010-02-27 15:58:28
 Last month  (last_month):2010-01
 Last month  (last_month_packed):201001
 The first day of the last month  (first_date_of_last_month):2010-01-01
 Last month, the last day  (last_date_of_last_month):2010-01-31
 Today the day of the week  (day_of_week):6
 Last hour  (last_hour):2010-02-27-14
 The current hour  (the_hour):15
 The current minutes  (the_minute):58
 The current seconds  (the_second):28
 The current year  (the_year):2010
 The current month  (the_month):2
 Current date  (the_date):27
 The day before yesterday  (days_ago 2):2010-02-25
 Tomorrow  (days_ago -1):2010-02-28
 The day after tomorrow  (days_ago -2):2010-03-01
 Ten days before the date of  (days_ago 10):2010-02-17
 Chinese date weeks  (chinese_date_and_week):2 On 27 January    Saturday
 Random numbers  (rand_digit):5
 Random numbers  (rand_digit):9
 Since 1970 the number of seconds to  (seconds_of_date):1267257508
 Since 1970 the number of seconds to  (seconds_of_date 2010-02-27):1267200000
 Since 1970 the number of seconds to  (seconds_of_date 2010-02-27 15:53:21):1267257201
 Since 1970 the number of seconds to the corresponding date  (date_of_seconds 1267200000):2010-02-27
 Since 1970 the number of seconds to the corresponding date time  (datetime_of_seconds 1267257201):2010-02-27 15:53:21
2008 Year is a leap year
2007 02 03  Date legitimate
2007 02 28  Date legitimate
2010 The number of days in February  (days_of_month 2 2010):28
2008 The number of days in February  (days_of_month 2 2008):29
分类:OS 时间:2010-02-27 人气:294
分享到:
blog comments powered by Disqus

相关文章

  • Linux and unix shell programming guide _ Part shell_ the background command in Chapter 3 2011-04-21

    Chapter 3, the background command When you work in a terminal or console, might not want to run a job and occupy as a screen, because there may be more important things to do, such as reading e-mail. For access to disk-intensive process, you may want

  • Linux, Shell programming bash internal command 2010-07-05

    bash shell package program includes a number of internal commands. Internal command in the directory list is invisible, they are provided by the Shell itself. Common internal commands: echo, eval, exec, export, readonly, read, shift, wait, and dot (.

  • linux shell programming Summary (Abstract) 2010-05-10

    Seldom written, easy to forget. Extract notes. linux shell programming summary http://blog.csdn.net/ltbook This week learning the unix / linux shell programming, refer to the "LINUX and UNIX Shell Programming Guide", David Tansley forward; Xu Ya

  • Linux Shell Programming Training [Reserved] 2010-06-24

    As the project needs, the recent need to write some shell scripts, suffer no basis for a number of documents reproduced in the first study are: On the variables, also need to know a few Linux commands associated. env zone used to display the user env

  • Introduction to Linux Shell Programming 2011-01-23

    Shell Programming Abstract: This article describes how to write with a large number of instances a shell script. Why do you want to shell programming in the Linux system, although there are a variety of graphical interface tools, but the shell is sti

  • Introduction to Linux shell programming [turn] 2011-04-25

    Shell itself is a program written in C language, it is the bridge between users of Linux. Shell is a command language is a programming language. As a command language, which interactively interpretation and implementation of user-entered commands; as

  • Introduction to shell programming under Linux 2011-04-27

    Typically, we enter the command from the command line every time you enter the system can be a response. Once we need to input a command and then a final time before they get results, this approach is clearly not efficient. To achieve this purpose, w

  • Linux Shell Programming Study Notes 2011-06-28

    In fact, as the command language to interpret and execute interactive commands entered by the user is only one aspect of Shell functions, Shell can also be used for programming, it provides a means to define the variables and parameters as well as a

  • linux and unix shell programming guide 2010-10-09

    linux and unix shell programming guide Preface Introduction Part translator directory shell Chapter 1, file security and permissions 1 1.1 Paper 1 1.2 File Type 2 1.3 Permissions 2 1.4 change the permissions bit 4 1.4.1 Symbolic Mode 4 1.4.2 chmod co

  • Linux, real-time tracking log4j log file bash script - enhanced the function of tail-f 2010-11-05

    Linux, real-time tracking log4j log file bash script - enhanced the function of tail-f This link: http://codingstandards.javaeye.com/blog/803686 (reprint, please indicate the source) Problem Description In the development of Java applications, we oft

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.222 (s). 12 q(s)