在类UNIX系统中,日期被存储为一个整数,其大小为自世界标准时间(UTC)1970年1月1日0时0分0秒起流逝的秒数。这个整数就是时间戳。在我们写脚本的时候经常使用到一些时间统计的工作,时间戳就很有用了。
date命令可以取得、设置时间和日期。具体用法如下
Usage: date [OPTION]... [+FORMAT] or: date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] Display the current time in the given FORMAT, or set the system date.可以用参数
date <+时间日期格式>:指定显示时使用的日期时间格式。
日期格式字符串列表
%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)
date Mon Nov 2 10:37:48 CST 2020 date +%s #这就可以获得时间戳 1604284679其实原理很简单,就是在工作开始时几下时间戳,工作结束时再记下时间戳。相减就得到耗费时间了。 脚本显示如下:
# testping.sh #! /bin/sh START_TIME_STAMP=`date +%s` ping www.baidu.com -c 4 END_TIME_STAMP=`date +%s` DELTA_TIME_STAMP=`expr $END_TIME_STAMP - $START_TIME_STAMP` echo "spead $DELTA_TIME_STAMP sec(s)."执行效果如下:
> sh -x ./testping.sh ++ date +%s + START_TIME_STAMP=1604285272 + ping www.baidu.com -c 4 PING www.a.shifen.com (61.135.169.121) 56(84) bytes of data. 64 bytes from 61.135.169.121: icmp_seq=1 ttl=55 time=1.35 ms 64 bytes from 61.135.169.121: icmp_seq=2 ttl=55 time=0.993 ms 64 bytes from 61.135.169.121: icmp_seq=3 ttl=55 time=0.986 ms 64 bytes from 61.135.169.121: icmp_seq=4 ttl=55 time=0.995 ms --- www.a.shifen.com ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 7010ms rtt min/avg/max/mdev = 0.986/1.081/1.352/0.159 ms ++ date +%s + END_TIME_STAMP=1604285284 ++ expr 1604285284 - 1604285272 + DELTA_TIME_STAMP=12 + echo 'spead 12 sec(s).' spead 12 sec(s).