检查参数是否是shell脚本中的有效日期时间

时间:2018-02-12 06:40:46

标签: linux bash shell

我正在Linux中编写一个bash shell脚本,该程序将接受date 08-FEB-18 11.45.18.844 AM作为参数。

我想知道是否有一种简单的方法来检查date time是否有效?

1 个答案:

答案 0 :(得分:3)

你可以获得一些创意,因为你有bash并将日期字符串映射到一个数组,然后可以使用date -d(以及另一个关联数组的帮助)轻松解析。一旦将日期/时间映射到数组元素并将其转换为自date -d的纪元以来的秒数,您只需检查date命令的返回以确定转换是成功还是失败。妥善处理退货:

#!/bin/bash

[ -n "$1" ] || {    ## validate one argument given
    printf "error: insufficient input\nusage: %s dd-mmm-yy hh.mm.ss.ms\n" \
    "${0##*/}"
    exit 1
}

oifs="$IFS"         ## save original Internal Field Separator
IFS=$' \t\n-.';     ## set IFS to break on - or .

dt=( $(echo $1) )   ## separate date into indexed array

[ "${#dt[@]}" -lt '7' ] && {    ## check all 7 components present
    printf "error: date doesn't match dd-mmm-yy hh.mm.ss.ms format\n"
    exit 1
}

IFS="$oifs"         ## reset original IFS

## create associative array mapping months to numerics
declare -A mo=(
    [JAN]=1
    [FEB]=2
    [MAR]=3
    [APR]=4
    [MAY]=5
    [JUN]=6
    [JUL]=7
    [AUG]=8
    [SEP]=9
    [OCT]=10
    [NOV]=11
    [DEC]=12
)

## any date after 30 considerd 1930, else considered 2000
[ "${dt[2]}" -gt '30' ] && dt[2]=$((${dt[2]} + 1000)) || \
dt[2]=$((${dt[2]} + 2000))

## use date to convert array contents to seconds since epoch
epochsec=$( date -d "${dt[2]}-${mo[${dt[1]}]}-${dt[0]} \
                    ${dt[3]}:${dt[4]}:${dt[5]}.${dt[6]}" +%s )

if [ "$?" -ne '0' ]; then   ## check if last return was error
    printf "error: invalid date.\n"
else    ## output good date
    printf "date: %s\n" "$(date -d @$epochsec)"
fi

示例使用/输出

$ bash chkcustomdt.sh "08-FEB-18 11.45.18.844"
date: Thu Feb  8 11:45:18 CST 2018

有很多方法可以解决这个问题,这只是第一个想到的方法。

相关问题