繁体   English   中英

Bash 脚本:我的减法问题

[英]Bash script : problem with my substraction

我想制作一个脚本来计算两个 curl 之间的下载时间差异。

例如,使用此命令:

curl -s -w 'total : %{time_total}\n' https://releases.ubuntu.com/20.04.1/ubuntu-20.04.1-desktop-amd64.iso -o ubuntu.iso >> total.txt

我的 curl 命令将每天运行,我想在当天的值和前一天的值之间进行减法。 为此,我将每天的time_total值保存在一个名为 total.txt 的外部文件中:

total : 77,844315
total : 95,531319
total : 91,270609
total : 79,185359
total : 94,861921

为此,这是我的脚本:

#!/bin/bash

Previous_value=$(cat total.txt| awk '{print $3}' | tail -n 2 | head -n 1 )
Current_value=$(cat total.txt | awk '{print $3}' | tail -n 2 | tail -n 1 )

echo "Yesterday download time : "$Previous_value"s"
echo "Today download time : "$Current_value"s"

test=$(($Current_value-$Previous_value))

echo "Download : + "$test"s"

Output:

Yesterday download time : 79,185359s
Today download time : 94,861921s
Download : + 185359s

结果应该是Download: + 15.676562s但目前的结果是Download: + 185359s 有人告诉我为什么吗?

对于更精确的数学使用bc 还要确保您输入的是有效数字。 bc仅解释用于分隔整数和小数部分的小数,因此您可能希望将这些逗号转换为小数: tr ',' '.'

代替:

echo $(( $A - $B ))

做:

bc -l <<< "$A - $B"

专门针对您的脚本:

#!/bin/bash

Previous_value=$(cat total.txt| awk '{print $3}' | tail -n 2 | head -n 1 | tr ',' '.')
Current_value=$(cat total.txt | awk '{print $3}' | tail -n 2 | tail -n 1 | tr ',' '.')

echo "Yesterday download time : "${Previous_value}"s"
echo "Today download time : "${Current_value}"s"

test=$( bc -l <<< "${Current_value} - ${Previous_value}" )

echo "Download : + "$test"s"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM