Skip to content
Advertisement

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}n' 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 ?

Advertisement

Answer

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"
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement