Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Percentage change - how to calculate it? How to get absolute value without bc?

I need to count a percentage change between two values.

The code I have here:

echo $time1
echo $time2
pc=$(( (($time2 - $time1)/$time1 * 100) ))
echo $pc

Brings such output in the console (with set -xe option)

+ echo 1800
1800
+ echo 1000
1000
+ pc=0
+ echo 0

The code inside the math expression seems to be written properly, still, I get -80 or so. Why is this happening to me?

The second part of the question. I have no access and I will have no access to the bc command. From what I heard it can give me the absolute value of the number I have.

So.. Without the bc command - will this be a good idea for an IF condition?

if (( (( "$pc" > 20 || (( "$pc" < -20 )); then...
like image 494
dziki Avatar asked Jan 09 '23 08:01

dziki


1 Answers

As you have mentioned that it's not necessary to do this in bash, I would recommend using awk:

awk -v t1="$time1" -v t2="$time2" 'BEGIN{print (t2-t1)/t1 * 100}'

Normally, awk is designed to process files but you can use the BEGIN block to perform calculations without needing to pass any files to it. Shell variables can be passed to it using the -v switch.

If you would like the result to be rounded, you can always use printf:

awk -v t1="$time1" -v t2="$time2" 'BEGIN{printf "%.0f", (t2-t1)/t1 * 100}'

The %.0f format specifier causes the result to be rounded to an integer (floating point with 0 decimal places).

like image 182
Tom Fenech Avatar answered Jan 27 '23 03:01

Tom Fenech