Linux shell 的date表示法

URL Link //n.sfs.tw/10080

2016-10-27 11:25:27 By 張○○

Linux shell中用 csh/tcsh

顯示前一天日期

$ /bin/date --date='1 day ago' +%Y%m%d%H%M%S
20161026214123

顯示前一週日期

$ /bin/date --date='1 week ago' +%Y%m%d%H%M%S
20161020214123

顯示前一月日期

$ /bin/date --date='1 month ago' +%Y%m%d%H%M%S
20160926214123

環境變數 locale

在date 如果叫用 %b的參數會顯示出月份的地區名稱,注意格式前的 '+' 代表的是要輸出的格式
$ date +%a%A%b%B%c%C
結果:
六週六 1月一月西元2016年10月27日 (週四) 15時30分35秒20

如果要用日期作為檔名,我們一般而言不喜歡檔名有中文字。例如檔名是2009Jan,你不希望取出的檔名是"2009一月",則就要把日期輸出改為英文,因此在Linux下先 叫用這一行:
$ export LC_TIME=en_US.utf8
$ date +%a%A%b%B%c%C
SatSaturdayJanJanuarySat 24 Jan 2009 03:31:36 PM CST20

 

有關shell 中date 格式(FORMAT)變數的意義

%  Literal %. <== 代表'%' 符號
-(hyphen)  Do not pad fields (default: pad fields with zeros).  <== 字元不足不用補0,預設有補0
_ (underscore)  Pad fields with space (default: zeros). <== 字元不足用空白補
%a Abbreviated weekday.
%b Abbreviated month name.
%c Country-specific date and time format.
%d Day of month (01-31).
%h Same as %b.
%j Julian day of year (001-366).
%k Hour in 24-hour format, without leading zeros (0-23).
%l Hour in 12-hour format, without leading zeros (1-12).
%m Month of year (01-12).
%n Insert a new line.
%p String to indicate a.m. or p.m.
%r Time in %I:%M:%S %p (12-hour) format.
%s Seconds since "the Epoch," which is 1970-01-01 00:00:00 UTC (a nonstandard extension).
%t Insert a tab.
%w Day of week (Sunday = 0).
%x Country-specific date format based on locale.
%y Last two digits of year (00-99).
%z RFC 822-style numeric time zone.
%A Full weekday.
%B Full month name.
%D Date in %m/%d/%y format.
%H Hour in 24-hour format (00-23).
%I Hour in 12-hour format (01-12).
%M Minutes (00-59).
%S Seconds (00-59).
%T Time in %H:%M:%S format.
%U Week number in year (00-53); start week on Sunday.
%V Week number in year (01-52); start week on Monday.
%W Week number in year (00-53); start week on Monday.
%X  Country-specific time format based on locale.
%Y Four-digit year (e.g., 2006).
%Z Time-zone name.

原文編修 2008-11-24 15:39:12