Merack

  • About
Merack
崭新万物正上升幻灭如明星
我却乌云遮目
  1. 首页
  2. Code
  3. 正文

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

2021-05-09

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

#!/bin/bash
#create By Merack
#[email protected]


#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

运行结果:

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: shell
最后更新:2024-12-20

Merack

起身向荒原

点赞
< 上一篇
下一篇 >

归档

  • 2025 年 3 月
  • 2025 年 2 月
  • 2024 年 12 月
  • 2024 年 6 月
  • 2024 年 4 月
  • 2021 年 5 月
  • 2020 年 6 月

分类

  • Code
  • CTF
  • Linux
  • 建站
  • 未分类

COPYRIGHT © 2024 Merack. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

cloudflare upyun 提供CDN服务