date 輸出每個月的日期? - Linux

Thomas avatar
By Thomas
at 2011-05-26T22:24

Table of Contents

其實跟coldnew的版本很像 部份簡化後附上簡易說明 如下:

#!/bin/sh

if [[ $1 == "--help" ]]; then
echo
echo "usage:"
echo
echo " mday --help => display this message"
echo " mday => day of current month"
echo " mday 5 2011 => day of the 05/2011 "
echo
else
if [[ $1 == "" ]] || [[ $2 == "" ]]; then
echo `cal` | awk '{print $NF}'
else
echo `cal $1 $2` | awk '{print $NF}'
fi
fi

將以上文字儲存為 mday 並給予執行權限 chmod +x mday

使用方法:

mday 或 mday --help 查看說明
mday 查看目前月份之日數
mday 查看選定月份之日數


操作原理:

原本cal執行結果如下

五月 2011
日 一 二 三 四 五 六
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

搭配 echo 使用 (即 echo `cal`) 可得到以下結果

五月 2011 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 \
19 20 21 22 23 24 25 26 27 28 29 30 31

原本的月曆變成了以空白為間隔的單行文字

最後使用 awk '{print $NF}' 將最後一個欄位取出

這時取得之文字 即為每個月的最後一天 也就是該月之日數


※ 引述《[email protected] (後山的破壞者)》之銘言:
: ※ 引述《[email protected] (啦 )》之銘言:
: > 請教一下,我知道 date 可以知道目前的時間日期以及前後天等這類的資訊,
: > 不知道它是否可以我給定它譬如: 2011年 2 月份,它會回傳給我 28 天;
: > 給他 2008 年 2 月,他會回傳給我 29 天。不知道是否可以實現?謝謝!
: 用以下指令可以搞定:
: cal `date '+%m'` `date '+%Y'` | grep . | fmt -1 | tail -1
: 若你想直接查詢某年某月
: example: 查詢 2008年2月
: cal 02 2008 | grep . | fmt -1 | tail -1
: 若寫成shell script的話:
: #!/bin/bash
:
: if [ "$1" = "" ]
: then YEAR=`date '+%Y'`
: else YEAR=$1
: fi
:
: if [ "$2" = "" ]
: then MONTH=`date '+%m'`
: else MONTH=$2
: fi
:
: DAY_IN_MONTH=`cal $MONTH $YEAR | grep . | fmt -1 | tail -1`
:
: echo "$YEAR/$MONTH has $DAY_IN_MONTH days"
:
: 假設你將這檔案存成 aa.sh
: 使用方法: ./aa.sh 2008 02
: 會得到 2008/02 has 29 days

--
Tags: Linux

All Comments

Anonymous avatar
By Anonymous
at 2011-05-29T00:20
謝謝! :>

Buffer Overflow 產生的Segmentation Fault

Thomas avatar
By Thomas
at 2011-05-26T22:00
大家好, 小弟菜鳥正在學習緩衝(buffer)溢位(overflow)攻擊,依據書上的code想看看實 際運作情況…我知道Ubuntu至少有二種防止Buffer Overflow 的方式,所以我用了如下的 方式: Step 0: 關閉 random memory address scheme ...

ubuntu 的 make 不能用

Iris avatar
By Iris
at 2011-05-26T21:40
我的是 Ubuntu 10.10 我下載了一個 tar.gz的檔案 並且以 tar -zxvf 解壓縮好了 也確認資料夾中有 INSTALL Makefile 等等的檔案 但是每當我輸入 make 就會出現 make: *** No targets specified and no makefil ...

關於用寫shell script執行wget去抓檔案

Jacob avatar
By Jacob
at 2011-05-26T21:22
超級感謝的~ 我稍微修改了一點點 把兩個for loop的邊界值 調整了一下 i的for loop改成1..73 j的for loop改成 0..99 這樣就有符合 我要抓檔的需求了 超級感謝你的~~ 我正在努力的搞懂 你寫的架構 謝謝你~ ※ 引述《windincloud (駭客先生不要來~~)》之銘言 ...

Linux Mint 11 “Katya” released!

Ida avatar
By Ida
at 2011-05-26T21:16
Linux Mint 11 Has Been Released http://blog.linuxmint.com/?p=1760 [載點] 台灣元智: http://ftp.oss.tw/pub/Mint/LinuxMint-ISO/stable/11/ -- Sent from Ubuntu - ...

關於用寫shell script執行wget去抓檔案

Robert avatar
By Robert
at 2011-05-26T20:49
#!/bin/bash for i in {0..73} do if [ ${i} -lt 10 ]; then dir=0${i}0 else dir=${i}0 fi mkdir ...