리눅스에서 date 명령어 사용하기
date는 리눅스에서 시스템 시간을 세팅하거나 출력하기 위해 사용하는 함수이다.
man date를 하면 아래와 같은 기본 사용법이 나온다.
주로 -d option으로 원하는 시간 문자열로 조정한후
format옵션으로 원하는 형태로 시간을 출력하는 방식으로 사용하고 있다.
아무 인자 없이 사용하면 현재 시간이 출력된다.
DATE(1) User Commands DATE(1)
NAME
date - print or set the system date and time
SYNOPSIS
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
DESCRIPTION
Display the current time in the given FORMAT, or set the system date.
Mandatory arguments to long options are mandatory for short options too.
-d, --date=STRING
display time described by STRING, not 'now'
-f, --file=DATEFILE
like --date once for each line of DATEFILE
-s, --set=STRING
set time described by STRING
-u, --utc, --universal
print or set Coordinated Universal Time
--help display this help and exit
--version
output version information and exit
아래는 -d 옵션으로 시간 표현을 문자열로 출력하는 예시이다.
# date
2016. 01. 24. (일) 12:46:30 KST
# 과거
date -d 'yesterday' # 어제
date -d '2 day ago' # 2일전
date -d '1 week ago' # 1주일전
date -d '1 month ago' # 1달전
date -d '1 year ago' # 1년전
date -d '10 second ago' # 10초전
date -d '20 minute ago' # 20분전
date -d '30 hour ago' # 30시간전
date -d '3 year 7 month ago' # 3년 7개월전
#미래
# 특정일 기준
# date -d '2015-01-25 + 1 day'
2015. 01. 26. (월) 00:00:00 KST
# date -d '2015-01-25 - 1 day'
2015. 01. 24. (토) 00:00:00 KST
# date -d '2015-01-25 - 1 month'
2014. 12. 25. (목) 00:00:00 KST
# date -d '2015-01-25 + 1 month'
2015. 02. 25. (수) 00:00:00 KST
f참고: http://steadypost.net/post/knowhow/id/8/관련 option은 아래와 같다
시간 표현을 하는 format 옵션의 사용방법은 아래와 같다.
FORMAT controls the output. Interpreted sequences are:
%% a literal %
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
참고로 쉘스크립트에서 시간표현을 변수에 담는 방법은 아래와 같다.
yesterday=$(date -d '1 day ago')
또는
yesterday=`date -d '1 day ago'`