shell中的时间值提取(date)
方法1
# date +%F
# date +%T
# cat time.sh
#!/bin/bash
DATE=`date +%F | sed 's/-//g'``date +%T | sed 's/://g'`
echo $DATE
# chmod u+x time.sh
# sh time.sh
2014082709352
方法2
“date +%Y%m%d%H%M%S”获取时间信息串
[we@h p]$ date +%Y%m%d%H%M%S;date
20160410021109
Sun Apr 10 02:11:09 CST 2016
方法3
“date +%s”获取绝对秒数(UTC),使用“-d”参数还原时间。
#!/bin/bash
print_date()
{
/bin/date
}
echo -n -e '\f$(date)\t\t| '
print_date
echo -n -e 'SEC=$(date +%s)\t| '
SEC=$(date +%s)
echo "$SEC"
echo -n -e '$(date -d @$SEC)| '
date -d @$SEC
[web@h p] sh date.sh
$(date) | Tue Apr 12 22:25:41 CST 2016
SEC=$(date +%s) | 1460471141
$(date -d @$SEC)| Tue Apr 12 22:25:41 CST 2016
生成与时间相关的文件名称
应用:
例如用命令替换的方式生成带有时间信息的文件名。
$ touch ./reslog-"`date`".txt
$ ll
total 0
-rw-r--r-- 1 root root 0 Sep 12 05:43 are
-rw-r--r-- 1 root root 0 Sep 12 05:43 reslog-Mon Sep 12 05:43:25 CST 2016.txt
-rw-r--r-- 1 root root 0 Sep 12 05:43 reslog-Mon Sep 12 05:43:36 CST 2016.txt
-rw-r--r-- 1 root root 0 Sep 12 05:43 reslog-Mon Sep 12 05:43:37 CST 2016.txt
-rw-r--r-- 1 root root 0 Sep 12 05:43 reslog-Mon Sep 12 05:43:38 CST 2016.txt
$ touch ./reslog-"`date +%s`".txt
$ ll
total 0
-rw-r--r-- 1 root root 0 Sep 12 05:43 are
-rw-r--r-- 1 root root 0 Sep 12 05:50 reslog-1473630651.txt
-rw-r--r-- 1 root root 0 Sep 12 05:50 reslog-1473630652.txt
-rw-r--r-- 1 root root 0 Sep 12 05:50 reslog-1473630653.txt
-rw-r--r-- 1 root root 0 Sep 12 05:50 reslog-1473630654.txt
$ touch ./reslog-"`date +%Y%m%d%H%M%S`".txt
$ ll
total 0
-rw-r--r-- 1 root root 0 Sep 12 05:43 are
-rw-r--r-- 1 root root 0 Sep 12 05:53 reslog-20160912055308.txt
-rw-r--r-- 1 root root 0 Sep 12 05:53 reslog-20160912055309.txt
-rw-r--r-- 1 root root 0 Sep 12 05:53 reslog-20160912055310.txt
* “date +%H%M%S”,这里的小时是“00~23”格式的,如果使用“date + %I”显示就是“01~12”格式的小时。
这个风格更加直观
$ touch ./reslog-"`date +%F_%T`".txt
$ ll
total 0
-rw-r--r-- 1 root root 0 Sep 12 06:00 are
-rw-r--r-- 1 root root 0 Sep 12 06:02 reslog-2016-09-12_06:02:18.txt
-rw-r--r-- 1 root root 0 Sep 12 06:02 reslog-2016-09-12_06:02:19.txt
-rw-r--r-- 1 root root 0 Sep 12 06:02 reslog-2016-09-12_06:02:20.txt
$ touch ./reslog-"`date +%F\ %T`".txt
$ ll
total 0
-rw-r--r-- 1 root root 0 Sep 12 06:00 are
-rw-r--r-- 1 root root 0 Sep 12 06:06 reslog-2016-09-12 06:06:18.txt
-rw-r--r-- 1 root root 0 Sep 12 06:06 reslog-2016-09-12 06:06:19.txt
-rw-r--r-- 1 root root 0 Sep 12 06:06 reslog-2016-09-12 06:06:20.txt
时间设置
命令:
date,打印、设定日期和时间
选项:
-d, --date=STRING
显示时间;不是当前时间,是字符串指定的时间。
-s, --set=STRING
设置时间
STRING:
“Sun, 29 Feb 2004 16:21:42 -0800”
“2014-02-29 16:21:42 -0800”
“2024-02-29 16:21 -0800”
“2034-02-29 -0800”
“2044-02-29 16:21:42”
“16:00 next Thursday”
“next Thursday”
例子:
设置时间
[root@hp430G2 ~]# date -s "2014-08-27 17:30:55"
显示时间
[weblogic@hp430G2 ~]$ date -d "20140312 17:22:21"
Wed Mar 12 17:22:21 CST 2014
[weblogic@hp430G2 ~]$ date -d "2014-03-12 17:22:21"
Wed Mar 12 17:22:21 CST 2014