Jake S Jake S - 1 month ago 19
Linux Question

BASH Arithmetic operation not working

The code below is meant to calculate the percentage completed when a file is getting dd.

percentDone=$(((varFileSize / backupSize) * 100)


I am able to debug the script running and the variables get assigned numbers. However as soon as the script runs this line percentDone remains at 0.

I have also tried this:

percentDone=$((varFileSize / backupSize))
percentDone=$((percentDone * 100))


Any ideas please let me know as really struggling with this problem!
Thank you!!

Answer

Since bash only supports integers you have to do the calculation other way around:

percentDone=$(varFileSize * 100 / backupSize)

Otherwise dividing anything less than backupSize with it will result in zero and multiplying it with anything won't help.