-1

i am new to bash script. I am making a script to calculate cpu usage. So what I am doing is calculating cpu usage and comparing with a predefined value i.e threshold value. But my if condition is always going wrong. Please help me to correct my script.

#!/bin/bash
#checking the cpu usage
cpu_usage=$( mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12 }')
cpu_threshold=1.00
if [ $cpu_usage > $cpu_threshold ] ; then
echo "The CPU utilization is above threshold : $cpu_usage %" 
else
echo "The CPU utilization is below threshold : $cpu_usage %" 
fi

Please do check the above script in bash beacause I have tried many ways but always if condition is giving wrong output.

codeforester
  • 39,467
  • 16
  • 112
  • 140

3 Answers3

2

@Ankit: Try: changing if [ $cpu_usage > $cpu_threshold ] to if [[ $cpu_usage > $cpu_threshold ]]

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 2
    I was thinking floating point operations don't work in Bash - now I realize, comparisons do work though arithmetic may not. See: http://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash – codeforester Feb 28 '17 at 06:32
  • @RavinderSingh13 can you help me with same above question with 'and' operator wither other condition of same type. like if [ $cpu_usage > $cpu_threshold ] and [[ $cpu_usage > $cpu_threshold ]] is it correct – Ankit Kushwaha Feb 28 '17 at 07:09
  • @AnkitKushwaha: Why you should put AND(&&) operator for same conditions? && operator should be when you want 2 different conditions should be TRUE at sametime. – RavinderSingh13 Feb 28 '17 at 13:17
0

use this to compare two float numbers

$cpu_usage'>'$cpu_threshold | bc -l
Harper Koo
  • 597
  • 5
  • 14
0

Here is the correct and complete answer of my question.

  #! /bin/bash
    #checking the cpu usage
    cpu_usage=$( mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12 }')
    cpu_threshold=70
    echo $cpu_usage
    echo $cpu_threshold
    if [[ $cpu_usage > $cpu_threshold ]] ; then
    echo "The CPU utilization is above threshold : $cpu_usage %" 
    else
    echo "The CPU utilization is below threshold : $cpu_usage %" 
    fi