shell指令碼獲取昨天今天本週週一本週週日本月第一天本月最後一天
阿新 • • 發佈:2018-12-05
偶爾在linux上需要做指令碼,並設定指令碼按照日期來計算相關資料,這時候就涉及到日期的獲取,這裡介紹簡單的幾個重要日期的獲取,分別是昨天,今天是本週的第幾天,本週週一,本週週日,本月第一天,本月最後一天。
指令碼獲取日期並格式化,思路都是相同的,首先獲取日期,然後給出格式化表示式。
昨天的獲取有兩種方式:
yesterday=`date -d '1 days ago' +%Y%m%d`
yesterday2=`date -d yesterday +%Y%m%d`
今天是本週的第幾天:
today=`date +%Y%m%d`
whichday=`date -d $today +%w`
當前週一:
monday=`date -d "$today -$[${whichday}-1] days" +%Y%m%d`
當前週日:
sunday=`date -d "$monday+6 days" +%Y%m%d`
當月第一天:
firstdate=`date +%Y%m01`
當月最後一天:
lastdate=`date -d"$(date -d"1 month" +%Y%m01) -1 day" +%Y%m%d`
綜合例項:date.sh
#!/bin/bash #昨日 yesterday=`date -d '1 days ago' +%Y%m%d` echo "yesterday is $yesterday." yesterday2=`date -d yesterday +%Y%m%d` echo "yesterday is $yesterday2 by 'date -d yesterday +%Y%m%d'." #今日 today=`date +%Y%m%d` echo "today is $today." #當前周的第幾天 whichday=$(date -d $today +%w) echo "today is $whichday day of this week." #當週的週一 monday=`date -d "$today -$[${whichday}-1] days" +%Y%m%d` #當週的週日 sunday=`date -d "$monday+6 days" +%Y%m%d` echo "monday is $monday of this week." echo "sunday is $sunday of this week." #當月第一天(這裡取巧用了01直接代替當月第一天的日期) firstdate=`date +%Y%m01` echo "the firstday of this month is $firstdate." #當月最後一天(當月第一天的後一個月第一天的前一天就是當月最後一天,有點繞) lastdate=`date -d"$(date -d"1 month" +%Y%m01) -1 day" +%Y%m%d` echo "the lastday of this month is $lastdate."
執行結果:
[[email protected] ~]# ./date.sh yesterday is 20181106. yesterday is 20181106 by 'date -d yesterday +%Y%m%d'. today is 20181107. today is 3 day of this week. monday is 20181105 of this week. sunday is 20181111 of this week. the firstday of this month is 20181101. the lastday of this month is 20181130.