温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在shell中打印指定日期的日历

发布时间:2021-05-08 17:16:34 来源:亿速云 阅读:502 作者:Leah 栏目:开发技术

怎么在shell中打印指定日期的日历?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

打印本月的日期

#! /bin/bash
#设置字体颜色
tiffcolor="\033[0;35m"
menucolor="\033[0;33m"
todaycolor="\033[0;35;44m"
start="\033[0m"

#计算各个日期
month=`date +%m`
day=`date +%d`
year=`date +%Y`
weekday=`date -d "$year-$month-01" +%w`
nextmonth=`expr $month + 1`
today=`date +%d`
#计算本月有多少天
differ=$(( ($(date -d "$year-$nextmonth-01" +%s) - $(date +%s))/(24*60*60) )) 
days=`expr $differ + $day`

#打印标题
echo -en "${menucolor}"
echo -en "\t  $year $month\n"
echo "SUN MON TUE WEN THU FRI SAT"
echo -en "${start}"

#打印空格
if [ $weekday -ne 0 ];then
for((i=1;i<=$weekday;i++))
do
  echo -n "  "
  echo -n " "
done
fi

#打印日期
for((i=1;i<=$days;i++))
do
  printf "%s" " "
  echo -en "${tiffcolor}"
  #今天高亮显示
    if [ $today -eq $i ];then
      echo -en "${todaycolor}"
    fi
  printf "%2d" $i
  echo -en "${start}"
  echo -en " "
  if [ $((($weekday+$i)%7)) == 0 ];then
    echo ""
  fi
#  printf "%3d " $i
done
echo ""

执行结果:

怎么在shell中打印指定日期的日历

扩展:给定任意日期,打印当月的日期

#! /bin/bash
#date=$1
tiffcolor="\033[0;35m"
menucolor="\033[0;33m"
todaycolor="\033[0;35;44m"
start="\033[0m"


if [ $# -ne 1 ];then
  echo "plz input the date"
  exit 1
fi
date=$1
count=`echo $date |grep -o '-'|wc -l`
if [ $count -ne 2 ];then
  echo "plz input correct date"
  exit 1
fi
year=`echo $date|cut -d "-" -f 1`
month=`echo $date|cut -d "-" -f 2`
day=`echo $date|cut -d "-" -f 3`
expr $year + $month + $day + 0 &>/dev/null
if [ $? -ne 0 ];then
  echo "plz input a correct date"
  exit 1
elif [ $month -gt 12 -o $month -eq 0 ];then
  echo "plz input the month between 1 and 12"
  exit 1
elif [ $day -gt 31 -o $day -eq 0 ];then
  echo "plz input the day between 1 and 31"
  exit 1
fi

#nextmonth=$(( $month + 1))
#month=`date -d "$date" +%m`
#day=`date -d "$date" +%d`
#year=`date -d "$date" +%Y`
weekday=`date -d "$year-$month-01" +%w`
if [ $month -eq 12 ];then
  newmonth=1
  newyear=`expr $year + 1`
else
  newyear=$year
  #nextmonth= expr $month + 1
  newmonth=`expr $month + 1`
fi
days=$(( ($(date -d "${newyear}-${newmonth}-01" +%s) - $(date -d "$year-$month-01" +%s))/(24*60*60) )) 
#echo $days
echo -en "${menucolor}"
echo -en "\t  $year $month\n"
echo "SUN MON TUE WEN THU FRI SAT"
echo -en "${start}"

if [ $weekday -ne 0 ];then
for((i=1;i<=$weekday;i++))
do
  echo -n "  "
  echo -n " "
done
fi


for((i=1;i<=$days;i++))
do
  printf "%s" " "
  echo -en "${tiffcolor}"
    if [ $day -eq $i ];then
      echo -en "${todaycolor}"
    fi
  printf "%2d" $i
  echo -en "${start}"
  echo -en " "
  if [ $((($weekday+$i)%7)) == 0 ];then
    echo ""
  fi
#  printf "%3d " $i
done
echo ""

执行结果:

怎么在shell中打印指定日期的日历

看完上述内容,你们掌握怎么在shell中打印指定日期的日历的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI