linux时间戳

date命令是显示或设置系统时间与日期。

很多shell脚本里面需要打印不同格式的时间或日期,以及要根据时间和日期执行操作。延时通常用于脚本执行过程中提供一段等待的时间。日期可以以多种格式去打印,也可以使用命令设置固定的格式。在类UNIX系统中,日期被存储为一个整数,其大小为自世界标准时间(UTC)1970年1月1日0时0分0秒起流逝的秒数。

参数

<+时间日期格式>:指定显示时使用的日期时间格式。

日期格式字符串列表

%H 小时,24小时制(00~23)
%M 分钟(00~59)
%s 从1970年1月1日00:00:00到目前经历的秒数
%S 显示秒(00~59)
%T 显示时间,24小时制(hh:mm:ss)
%X 显示时间的格式(%H:%M:%S)

##shell下的时间加减法就是根据时间戳来实现的,时间戳对我们在shell下的操作非常的有用:
1.计算指定日期的时间戳:date -d "2018-12-05 19:45:44" +%s
[machao@iZ233xdnwmfZ ~]$ date -d "2018-12-05 19:45:44" +%s
1544010344
2.计算当天的时间戳:date +%s
[machao@iZ233xdnwmfZ ~]$ date +%s
1527833952
3.如果知道某个时间戳,也可以计算出这个时间戳对应的时间日期
[machao@iZ233xdnwmfZ ~]$ date +%s
1527835881
[machao@iZ233xdnwmfZ ~]$ date --date=@1527835881
Fri Jun  1 14:51:21 CST 2018
[machao@iZ233xdnwmfZ ~]$ date
Fri Jun  1 14:51:35 CST 2018

ps:需求

老大让写个脚本,监控一个进程, 当着这个进程连续运行超过15分钟,就杀掉

#!/bin/bash
while true
do
##进程的pid
pid=$(ps -ef|grep omjs|grep -v grep|grep -v 'sh'awk 'NR==1{print $2}')

##进程的执行时间
PID=$(ps -ef|grep omjs|grep -v grep|awk 'NR==1{print $5}')

##进程执行时间的时间戳
time=$(date -d $PID +%s)

##当前系统时间的时间戳
time1=$(date +%s)

##系统时间戳减去进程执行时间的时间戳
time2=`expr $time1 - $time`

##执行时间小于900秒就kill
if [ $time2 -gt 900 ]
then
kill $pid
fi
sleep 180
done
View Code
ps :执行过程
[root@iZ233xdnwmfZ machao]# sh -x kill-js-minut.sh 
+ true
++ ps -ef
++ grep omjs
++ grep -v grep
++ grep -v sh
++ awk 'NR==1{print $2}'
+ pid=4973
++ ps -ef
++ grep omjs
++ grep -v grep
++ awk 'NR==1{print $5}'
+ PID=15:23
++ date -d 15:23 +%s
+ time=1527837780
++ date +%s
+ time1=1527838266
++ expr 1527838266 - 1527837780
+ time2=486
+ '[' 486 -gt 900 ']'
+ sleep 180
View Code
 

 


猜你喜欢

转载自www.cnblogs.com/mclzy/p/9121894.html