shell编程:输入一个人的出生日期,计算此人今年多少岁,并计算今天距此人今年生日还有多少天

做实验时碰的到一道shell编程题:
输入一个人的出生日期,计算此人今年多少岁,并计算今天距此人今年生日还有多少天
本来想偷懒百度抄一下的结果翻了几页都没有, 算了还是自己写吧
脚本很简单, 主要是用date命令

#!/bin/bash
#create By Merack
#merack@qq.com


#get the current year, month, day
currentYear=`date +"%Y"`
currentMonth=`date +"%m"`
currentDay=`date +"%d"`

#check whether the birthday has passed in this year 
if [[ currentMonth -lt $2  ]]
then
    let "passFlag=0"
elif [[ currentMonth -eq $2 ]]
then
    if [[ currentDay -gt $3  ]]
    then
        let "passFlag=1"
    else
        let "passFlag=0"
    fi
else
    let "passFlag=1"
fi

#get age
if [[ $passFlag -eq 0  ]] 
then
    let "age=$currentYear-$1-1"
else
    let "age=$currentYear-$1"
fi
echo "your age: $age"


#get next Birthday
if [[ passFlag -eq 1 ]]
then
    echo "Your birthday has passed in this year"
        let "nextYea=currentYear+1"
        nextBirthday=$nextYea-$2-$3
        nowStr=`date +"%s"`
        nextBirStr=`date -d "$nextBirthday" +"%s"`
        let "interval=(nextBirStr-nowStr)/60/60/24"
        echo "Your next birthday is: $nextBirthday and $interval days left"
else
    nextBirthday=$currentYear-$2-$3
    nowStr=`date +"%s"`
    nextBirStr=`date -d "$nextBirthday" +"%s"`
    let "interval=(nextBirStr-nowStr)/60/60/24"
    echo "Your next birthday is: $nextBirthday and $interval days left"
fi

运行结果:

pic1.png

This article was updated on April 30, 2023