将浮点变量转换为整数?
如果页面加载时间超过 6 秒,下面所示的 shell 脚本将显示警告。问题是 myduration
变量不是整数。如何将其转换为整数?
myduration=$(curl http://192.168.50.1/mantisbt/view.php?id=1 -w %{time_total}) > /dev/null ; \
[[ $myduration -gt 1 ]] && echo "`date +'%y%m%d%H%M%S'
加载页面花费了超过 6 秒 http://192.168.50.1/mantisbt/view.php?id=1
The shell script shown below will show a warning if the page takes more than 6 seconds to load. The problem is that the myduration
variable is not an integer. How do I convert it to integer?
myduration=$(curl http://192.168.50.1/mantisbt/view.php?id=1 -w %{time_total}) > /dev/null ; \
[[ $myduration -gt 1 ]] && echo "`date +'%y%m%d%H%M%S'
It took more than 6 seconds to load the page http://192.168.50.1/mantisbt/view.php?id=1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设 $myduration 是小数或整数
Assuming $myduration is a decimal or integer
你可以这样做:
我在 bash 上使用它。
You can do this:
I am using this on bash.
这还不完全清楚,但我认为您是在问如何在
bash
中将浮点值 (myduration
) 转换为整数。这样的事情可能会对您有所帮助,具体取决于您想要对数字进行舍入的方式。用法示例:
It's not entirely clear, but I think you're asking how to convert a floating-point value (
myduration
) to an integer inbash
. Something like this may help you, depending on which way you want to round your number.Example usage:
从变量中删除页面内容:
当我尝试您的命令时,
myduration
包含我在测试中使用的 URL 处的页面 HTML 内容以及时间值。通过添加-s
来抑制进度条,并将-o /dev/null
添加到curl
的选项中,我能够删除重定向到/dev/null
并仅保存myduration
中的时间。由于
myduration
的值可能很短,因此您可以使用ire_and_curses
显示技术,该技术通常会产生零,其结果是小于您正在测试的 1(但请注意,您的日志消息显示“6 秒”)。更精细的分辨率:
如果您想要进行更精细的分辨率测试,您可以使用如下技术将
myduration
乘以 1000:编辑:此版本的
mult1000
可以正确处理“0.234”、“1”、“2.”、“3.5”等值和“6.789”。对于超过三位小数的值,无论值如何,多余的数字都会被截断而不进行四舍五入(“1.1119”变为“1.111”)。
您的脚本进行了我上面提到的更改并使用
mult1000
(使用我自己的示例时间):这里它被分成多行(并简化),以使其在这个答案中更具可读性:
Eliminate page contents from the variable:
When I tried your command,
myduration
contained the HTML contents of the page at the URL I used in my test plus the time value. By adding-s
to suppress the progress bar and adding-o /dev/null
to the options forcurl
, I was able to remove the redirect to/dev/null
and have only the time saved inmyduration
.Since the value of
myduration
is likely to be short, you can use the techniqueire_and_curses
shows which will often yield zero as its result which would be less than the 1 you are testing for (note that your log message says "6 seconds", though).Finer resolution:
If you'd like to have a finer resolution test, you can multiply
myduration
by 1000 using a technique like this:Edit: This version of
mult1000
properly handles values such as "0.234", "1", "2.", "3.5"and "6.789". For values with more than three decimal places, the extra digits are truncated without rounding regardless of the value ("1.1119" becomes "1.111").
Your script with the changes I mentioned above and using
mult1000
(with my own example time):Here it is broken into multiple lines (and simplified) to make it more readable here in this answer: