Bash – Subtract floating numbers in shell script

arithmeticbashkshlinuxshell-script

I'm trying to do some calculation in shell script with CPU usage. Which return floating point number. But when I subtract this number I'm getting error. See the following code and error.

Code

#!/bin/sh

CPU_IDLE=98.67
echo $CPU_IDLE
CPU_USAGE=$(( 100 - $CPU_IDLE ))
echo $CPU_USAGE

Error

./poc.sh: line 14: 100 - 98.67 : syntax error: invalid arithmetic operator (error token is ".67 ")

Best Answer

Neither bash nor ksh can perform floating point arithmetic (ksh93 supports that if I remember correctly). I recommend to switch to zsh or run external tool like bc:

$ CPU_IDLE=98.67
$ echo "$CPU_IDLE"
$ CPU_USAGE=$( bc <<< "100 - $CPU_IDLE" )
$ echo "$CPU_USAGE"
1.33
Related Question