3

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 ")
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
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.