如何在shell脚本中接受日期时间组合?

时间:2017-03-03 16:50:14

标签: bash shell unix

我希望通过用户传递参数来接受日期时间值,并希望在shell脚本中验证它。我怎么做到这一点,我尝试了以下方式,但失败了:

./program.sh 12-10:12:11     (In this 12 is date and other is time)

我将此作为参数传递并在shell脚本

中接受它
dtime=$1

if ! [ "`date '+%d-%H:%M:%S' -d $dtime 2>/dev/null`" = "$dtime" ]
then
echo $dtime is NOT a valid date format, use the d-H:M:S format
exit 0
fi

echo $dtime

但显示日期无效。

1 个答案:

答案 0 :(得分:3)

问题是提供给date命令的格式仅控制输出,而不控制输入(使用--date选项传递)。人们需要提供一些date会理解的格式。例如,可以手动用空格替换输入中的破折号,在当前年/月之前添加并使用此修改后的字符串进行测试:

#!/usr/bin/env bash

#date/time string is passed as first argument
dtime=$1

#replace first occurrence of - in $dtime with space
#and prepend the current year/month/
#This will for example
#transform the input "12-10:12:11" to "2017/03/12 10:12:11", i.e.,
#into a format which `date` understands. The reason for this is
#to provide complete date specification, otherwise `date`
#would complain that the date is invalid.  
s=$(date +'%Y/%m/')${dtime/-/ }

#feed the transformed input obtained in previous step to the
#`date` command and print the output in the required '%d-%H:%M:%S' format
x=$(date +'%d-%H:%M:%S' --date="$s" 2> /dev/null)

#finally, check if this formatted value equals the original input or not
if [ "${x}" != "${dtime}" ]
then
    echo "$dtime is NOT a valid date format, use the d-H:M:S format"
    exit 0
fi

echo $dtime