如何计算bash脚本中经过的时间? [英] How to calculate time elapsed in bash script?

查看:74
本文介绍了如何计算bash脚本中经过的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用date +"%T"打印开始时间和结束时间,结果如下:

I print the start and end time using date +"%T", which results in something like:

10:33:56
10:36:10

如何计算和打印这两者之间的差异?

How could I calculate and print the difference between these two?

我想得到类似的东西:

2m 14s

推荐答案

Bash有一个方便的SECONDS内置变量,该变量跟踪自启动外壳以来经过的秒数.分配给该变量后,该变量将保留其属性,赋值后返回的值是指赋值以来的秒数加上赋值.

Bash has a handy SECONDS builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.

因此,您可以在启动定时事件之前将SECONDS设置为0,在事件之后简单地读取SECONDS,并在显示之前进行时间算术.

Thus, you can just set SECONDS to 0 before starting the timed event, simply read SECONDS after the event, and do the time arithmetic before displaying.

SECONDS=0
# do some work
duration=$SECONDS
echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."

由于此解决方案不依赖date +%s(这是GNU扩展),因此可以移植到Bash支持的所有系统中.

As this solution doesn't depend on date +%s (which is a GNU extension), it's portable to all systems supported by Bash.

这篇关于如何计算bash脚本中经过的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆