在bash中生成特定日期

问题描述 投票:2回答:1

嗨我写下了一些bash来生成格式为YYYYMMDD的日期。

我知道这不完美,但最后的事情将是:

生成两个相隔31天的2个日期,从今天至少一天开始,而今年年底结束。格式为YYYYMMDD

month="$(awk -v min=1 -v max=12 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')"
day="$(awk -v min=1 -v max=31 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')"
year="$(date +%Y)"



if (( "${month}" < 10 )); then
    month_proper="$(echo 0"${month}")"
else
month_proper="$(echo "${month}")"
fi
if (( "${day}" < 10 )); then
    day_proper="$(echo 0"${day}")"

else
day_proper="$(echo "${day}")"
fi



echo month "${month}"
echo month with 0 if smaller than 10 : "${month_proper}"
echo day "${day}"
echo day with 0 smaller than 10 : "${day_proper}"

ok="$(date -d ""$year""${month_proper}""${day_proper}"" +"%Y%m%d")"
echo date with proper format "${ok}"
date -d "$year""${month_proper}""${day_proper}"

我必须在哪个方向扩展此脚本才能获得最终结果?我已经有了日期生成,但没有检查是否提前一天。

bash shell date random
1个回答
0
投票

要求几乎完全指定范围(明年12月31日至1月31日),所以你可以写

a_fmt=`date -d "tomorrow" +%Y1231`
a_num=`date -d "$a_fmt" +%s`

b_num=$(( a_num + 31 * 24 * 3600 ))
b_fmt=`date -d @$b_num +%Y%m%d`

echo "Range is '$a_fmt'..'$b_fmt'"
© www.soinside.com 2019 - 2024. All rights reserved.