如何计算在bash脚本的时间差? [英] How to calculate time difference in bash script?

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

问题描述

我用日期+%T,这将导致像打印起始和结束时间:

 十时33分56秒
十时36分10秒

我怎么能计算和打印这两者之间有什么区别?

我想获得这样的:

 2米14S


解决方案

Bash有可跟踪,因为外壳是已通过的秒数一个方便的内建变量启动。当分配与分配后返回的值是自分配加上指定值的秒数这个变量保留其属性。

因此​​,您可以只设置 0开始定时事件前,只需读在事件发生后和显示之前做对的时候算术。

 秒= 0
# 做一些工作
持续时间= $秒
回声$(($时间/ 60))分$(($持续时间60%))秒钟以后。

由于该解决方案不依赖于日期+%S (这是一个GNU扩展名),它移植到被Bash支持的所有系统。

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?

I would like to get something like:

2m 14s

解决方案

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.

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."

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天全站免登陆