Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

linux - Bash script : problem with my substraction

I would like to make a script that will calculate the difference of download time between two curl.

For example with this command :

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

My curl command will be run each day and I would like to make a substraction between the value of the day and the value of the previous day. For that, I will save the time_total value of each day in an external file called total.txt :

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

For that, this is my script :

#!/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

The result should be Download : + 15.676562s but currently the result is Download : + 185359s. Someone to tell me why ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For more precise math use bc. Also make sure you are entering valid numbers. bc only interprets decimals for separating whole and fractional components so you may want to translate those commas to decimals: tr ',' '.'

Instead of:

echo $(( $A - $B ))

Do:

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

Specifically for your script:

#!/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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...