Chinaunix首页 | 论坛 | 博客
  • 博客访问: 522699
  • 博文数量: 80
  • 博客积分: 1496
  • 博客等级: 上尉
  • 技术积分: 1292
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-18 11:24
个人简介

IT码农一个~

文章分类

全部博文(80)

文章存档

2020年(3)

2019年(7)

2017年(1)

2016年(2)

2015年(2)

2014年(26)

2013年(26)

2012年(2)

2011年(1)

2010年(1)

2008年(9)

我的朋友

分类: LINUX

2013-03-14 15:52:28

最近由于项目需要,需求每天对前一天的日志做备份和数据库导入操作。
在网上找了好几个如何使用shell获取前一天时间的方法,
下面一一为大家介绍:

1) 最简单、直接的方式
   前一天的日期
  $date -d"1 day ago" +"%Y%m%d"

  前一个月的日期
  $date -d"1 month ago" +"%Y%m%d"

  类似的还有
  $date -d"-1 day ago 1 month ago" +"%Y%m%d"
  $date -d"1 day ago -1 year ago 1 month ago" +"%Y%m%d"

2) 通过修改时区来做
    默认时区设置应该为 TZ=CST-8

    TZ=CST+16  (设置时区比-8时区晚24小时,即为+16) 
    export TZ
    yesterday_date=`date '+%Y%m%d'` (取得昨天的日期)
    TZ=CST-8   (复位时区为 -8)
    export TZ

3) 最复杂的,想练shell编程的可以使用
  # Set the current month day and year.
     month=`date +%m`
     day=`date +%d`
     year=`date +%Y`

    # Add 0 to month. This is a
    # trick to make month an unpadded integer.
    month=`expr $month + 0`

    # Subtract one from the current day.
    day=`expr $day - 1`

     # If the day is 0 then determine the last
    # day of the previous month.
    if [ $day -eq 0 ]; then

    # Find the preivous month.
    month=`expr $month - 1` 

    # If the month is 0 then it is Dec 31 of
   # the previous year.
   if [ $month -eq 0 ]; then
    month=12
   day=31
   year=`expr $year - 1` 

    # If the month is not zero we need to find
   # the last day of the month.
    else
    case $month in
    1|3|5|7|8|10|12) day=31;;
    4|6|9|11) day=30;;
    2)
    if [ `expr $year % 4` -eq 0 ]; then
     if [ `expr $year % 400` -eq 0 ]; then
    day=29
    elif [ `expr $year % 100` -eq 0 ]; then
    day=28
    else
    day=29
   fi
     else
   day=28
    fi
    ;;
    esac
    fi
   fi

# Print the month day and year.
echo $month $day $year
exit 0 

参考文献:

http://ceoli.blog.hexun.com/28085191_d.html
http://blog.itpub.net/post/7167/455452


阅读(2111) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~