Bash脚本来计算经过的时间 [英] Bash script to calculate time elapsed

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

问题描述

我正在用bash编写脚本来计算执行命令所花费的时间,请考虑:

I am writing a script in bash to calculate the time elapsed for the execution of my commands, consider:

STARTTIME=$(date +%s)
#command block that takes time to complete...
#........
ENDTIME=$(date +%s)
echo "It takes $($ENDTIME - $STARTTIME) seconds to complete this task..."

我想我的逻辑是正确的,但是最终得到了以下打印输出:

I guess my logic is correct however I end up with the following print out:

完成此任务需要几秒钟..."

"It takes seconds to complete this task..."

我的字符串评估有什么问题吗?

Anything wrong with my string evaluation?

我相信bash变量是无类型的,但我仍然希望bash中有从字符串到整数"的方法.

I believe bash variables are untyped, I would love if there is a "string to integer" method in bash nevertheless.

推荐答案

$(())$[]均可用于计算算术运算的结果.您正在使用$(),它只是将字符串作为命令评估.这有点微妙的区别.希望这会有所帮助.

Either $(()) or $[] will work for computing the result of an arithmetic operation. You're using $() which is simply taking the string and evaluating it as a command. It's a bit of a subtle distinction. Hope this helps.

正如小叮当在对此答案的评论中指出的那样,不推荐使用$[],而应该优先使用$(()).

As tink pointed out in the comments on this answer, $[] is deprecated, and $(()) should be favored.

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

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