bash 验证 shell 脚本中的日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18731346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:10:38  来源:igfitidea点击:

Validate date format in a shell script

bashshelldateunixif-statement

提问by Jairo Franchi

I have to create a Shell Script wherein one of the parameters will be the date in the format dd/mm/yyyy. My question is, how can I check if the Date passed as parameter really follows this Date Format? I tried to use the grep command as below:

我必须创建一个 Shell 脚本,其中一个参数是 dd/mm/yyyy 格式的日期。我的问题是,如何检查作为参数传递的日期是否真的遵循此日期格式?我尝试使用 grep 命令如下:

if echo "" | grep -q '^[0-3][0-9]/[0-1][0-9]/[0-9]\{4\}$'

but it didn't give the correct format because the day for example can be 33, 34, (...), that is not really the correct format. Anyone know something that can really check if the date passed really follows the format dd/mm/yyyy ?

但它没有给出正确的格式,因为例如日期可以是 33、34、(...),这并不是真正正确的格式。任何人都知道可以真正检查通过的日期是否真的遵循 dd/mm/yyyy 格式?

回答by P??x?L?

Use date

使用日期

date "+%d/%m/%Y" -d "09/99/2013" > /dev/null  2>&1
 is_valid=$?

If you do not get 0 then date is in invalid format.

如果您没有得到 0,则日期格式无效。

回答by Vic Seedoubleyew

The simplest solution, that still works perfectly, is the following :

最简单的解决方案仍然可以完美运行,如下所示:

if [[  =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "" >/dev/null 2>&1
   ...

It consists in combining 2 checks :

它包括结合 2 个检查:

  • the first part checks that $1is of this format : NNNN-NN-NN
  • the second part checks that it is a valid date
  • 第一部分检查$1是这种格式:NNNN-NN-NN
  • 第二部分检查它是否是有效日期

You need the two checks because :

您需要两项检查,因为:

  • if you don't do the first check, datewill exit with code 0 even if your variable is a valid date in another format
  • if you don't do the second check, then you can end up with a 0 even for variables such as 2016-13-45
  • 如果您不进行第一次检查,date即使您的变量是另一种格式的有效日期,也会以代码 0 退出
  • 如果您不进行第二次检查,那么即使对于诸如 2016-13-45

回答by Karl Kowallis

This function expects 2 strings,a format string, a date string

此函数需要 2 个字符串,一个格式字符串,一个日期字符串

The format string uses the codes from the date command but does not include the '+'

格式字符串使用 date 命令中的代码,但不包括“+”

The function returns 0 if the provided date matches the given format, otherwise it returns 1

如果提供的日期与给定的格式匹配,则该函数返回 0,否则返回 1

Code (my_script.sh)

代码 (my_script.sh)

#!/bin/bash

datecheck() {
    local format="" d=""
    [[ "$(date "+$format" -d "$d" 2>/dev/null)" == "$d" ]]
}

date_test=""

echo $date_test
if datecheck "%d %b %Y" "$date_test"; then
    echo OK
else
    echo KO
fi

Output

输出

$ ./my_script.sh "05 Apr 2020"
05 Apr 2020
OK
$ ./my_script.sh "foo bar"
foo bar
KO

回答by chelabim

#! /bin/bash

isDateInvalid()
{
    DATE=""

    # Autorized separator char ['space', '/', '.', '_', '-']
    SEPAR="([ \/._-])?"

    # Date format day[01..31], month[01,03,05,07,08,10,12], year[1900..2099]
    DATE_1="((([123][0]|[012][1-9])|3[1])${SEPAR}(0[13578]|1[02])${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[01..30], month[04,06,09,11], year[1900..2099]
    DATE_2="(([123][0]|[012][1-9])${SEPAR}(0[469]|11)${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[01..28], month[02], year[1900..2099]
    DATE_3="(([12][0]|[01][1-9]|2[1-8])${SEPAR}02${SEPAR}(19|20)[0-9][0-9])"

    # Date format day[29], month[02], year[1904..2096]
    DATE_4="(29${SEPAR}02${SEPAR}(19|20(0[48]|[2468][048]|[13579][26])))"

    # Match the date in the Regex

    if ! [[ "${DATE}" =~ "^(${DATE_1}|${DATE_2}|${DATE_3}|${DATE_4})$" ]]
    then
        echo -e "ERROR - '${DATE}' invalid!"
    else
        echo "${DATE} is valid"
    fi
}

echo
echo "Exp 1: "`isDateInvalid '12/13/3000'`
echo "Exp 2: "`isDateInvalid '12/11/2014'`
echo "Exp 3: "`isDateInvalid '12 01 2000'`
echo "Exp 4: "`isDateInvalid '28-02-2014'`
echo "Exp 5: "`isDateInvalid '12_02_2002'` 
echo "Exp 6: "`isDateInvalid '12.10.2099'`
echo "Exp 7: "`isDateInvalid '31/11/2000'`

回答by augurar

First, check the form of the input using the regex. Then use awk to switch to mm/dd/yyyy and use date to validate. You can use the following expression in your ifstatement:

首先,使用正则表达式检查输入的形式。然后使用 awk 切换到 mm/dd/yyyy 并使用 date 进行验证。您可以在if语句中使用以下表达式:

echo "" | egrep -q '^[0-3][0-9]/[0-1][0-9]/[0-9]{4}$' && date -d "$(echo "" | awk 'BEGIN{FS=OFS="/"}{print "/""/"}')" >/dev/null 2>&1

回答by konsolebox

Simplest way for dd/mm/yyyyexactly in Bash is:

dd/mm/yyyy在 Bash 中最简单的方法是:

if [[  == [0-3][0-9]/[0-1][0-9]/[0-9][0-9][0-9][0-9] ]]

Or

或者

if [[  =~ ^[0-3][0-9]/[0-1][0-9]/[0-9]{4}$ ]]

回答by VDR

How about using awk:

如何使用awk

echo "31/12/1999" | awk  -F '/' '{ print ( <= 31 &&  <= 12 && match(, /^[1-9][1-9][1-9][1-9]$/)) ? "good" : "bad" }'

It prints "good" if its valid date else prints "bad"

如果有效日期则打印“good”,否则打印“bad”

回答by javaPlease42

Here's a function to do some data validation this:

这是一个执行一些数据验证的函数:

# Script expecting a Date parameter in MM-DD-YYYY format as input
verifyInputDate(){
    echo ${date} | grep '^[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]$'
    if [ $? -eq 0 ]; then
         echo "Date is valid"
     else
          echo "Date is not valid"
     fi
}

回答by Manikandan

`X="2016-04-21" then check for the below value being 1 or 0.

`X="2016-04-21" 然后检查下面的值是 1 还是 0。

cal echo $x | cut -c 6-7echo $x | cut -c 1-42>/dev/null | grep -c echo $x | cut -c 9-10

校准echo $x | cut -c 6-7echo $x | cut -c 1-42>/dev/null | grep -cecho $x | cut -c 9-10

If the value is 1, then it's valid, else it's not valid.

如果值为 1,则它是有效的,否则它是无效的。

回答by Felipe

I wrote this bash script to validate date. I can accept mont as alphanumeric.

我写了这个 bash 脚本来验证日期。我可以接受 mont 作为字母数字。

#!/bin/bash

function isDateValid {
    DATE=

    if [[ $DATE =~ ^[0-9]{1,2}-[0-9a-zA-Z]{1,3}-[0-9]{4}$ ]]; then
        echo "Date $DATE is a number!"
        day=`echo $DATE | cut -d'-' -f1`
        month=`echo $DATE | cut -d'-' -f2`
        year=`echo $DATE | cut -d'-' -f3`

                if [ "$month" == "01" ] || [ "$month" == "1" ]; then
                        month="Jan"
                elif [ "$month" == "02" ] || [ "$month" == "2" ]; then
                        month="Feb"
                elif [ "$month" == "03" ] || [ "$month" == "3" ]; then
                        month="Mar"
                elif [ "$month" == "04" ] || [ "$month" == "4" ]; then
                        month="Apr"
                elif [ "$month" == "05" ] || [ "$month" == "5" ]; then
                        month="May"
                elif [ "$month" == "06" ] || [ "$month" == "6" ]; then
                        month="Jun"
                elif [ "$month" == "07" ] || [ "$month" == "7" ]; then
                        month="Jul"
                elif [ "$month" == "08" ] || [ "$month" == "8" ]; then
                        month="Aug"
                elif [ "$month" == "09" ] || [ "$month" == "9" ]; then
                        month="Sep"
                elif [ "$month" == "10" ]; then
                        month="Oct"
                elif [ "$month" == "11" ]; then
                        month="Nov"
                elif [ "$month" == "12" ]; then
                        month="Dec"
                fi

        ymd=$year"-"$month"-"$day
        echo "ymd: "$ymd
        dmy=$(echo "$ymd" | awk -F- '{ OFS=FS; print ,, }')
        echo "dmy: "$dmy
        if date --date "$dmy" >/dev/null 2>&1; then
                echo "OK"
            return 0
        else
                echo "NOK"
            return 1
        fi
    else
        echo "Date $DATE is not a number"
        return 1
    fi
}


if isDateValid "15-15-2014"; then
    echo "date is valid =)"
else
    echo "bad format date"
fi
echo "==================="
if isDateValid "15-12-2014"; then
        echo "date is valid =)"
else
        echo "bad format date"
fi
echo "==================="
if isDateValid "15-Dec-2014"; then
        echo "date is valid =)"
else
        echo "bad format date"
fi
echo "==================="
if isDateValid "1-May-2014"; then
        echo "date is valid =)"
else
        echo "bad format date"
fi
echo "==================="
if isDateValid "1-1-2014"; then
        echo "date is valid =)"
else
        echo "bad format date"
fi
echo "==================="
if isDateValid "12-12-2014"; then
        echo "date is valid =)"
else
        echo "bad format date"
fi