4

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 ")
sugunan
  • 423
  • 3
  • 7
  • 18
  • 2
    see [How to do integer & float calculations, in bash or other languages/frameworks?](https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks) – Evgeny Vereshchagin Aug 19 '15 at 15:03

2 Answers2

7

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
jimmij
  • 46,064
  • 19
  • 123
  • 136
1

Even though you used the tag in your question, the script starts with the #!/bin/sh hashbang, which will rarely give you a korn shell.

The rest of the code works fine with ksh (AT&T ksh93) on ubuntu 14.04:

$ ksh poc.sh
98.67
1.33

$ ls -lL /bin/ksh*
-rwxr-xr-x 1 root root 1509040 Jan  9  2013 /bin/ksh
-rwxr-xr-x 1 root root 1509040 Jan  9  2013 /bin/ksh93
Henk Langeveld
  • 752
  • 5
  • 16