0

I'm a newbie at bash scripting and I'm trying to write a script that if the memory utilization is greater than 80% it will display a message.

Here's the code:

#!/bin/sh

ramusage=$(free | awk '/Mem/{printf("RAM Usage: %.2f\n"), $3/$2*100}'| awk '{print $3}')

if [ $ramusage -gt 80 ]; then
    echo "Danger! Memory usage is  $ramusage = critical"
else
    echo "Chill.. Ram usage is $ramusage = normal"
fi

Unfortunately, after running the script I encountered the following error:

line 5: [: 15.95: integer expression expected

At this point, I'm not sure if my script is running correctly or what the error means. Any help would be appreciated.

accdias
  • 5,160
  • 3
  • 19
  • 31
  • `%.2f` generates a floating-point number, not an integer. Bash only supports integer math. – Charles Duffy Apr 25 '21 at 19:03
  • As the error says, Bash doesn't handle float point numbers. Replace `awk '/Mem/{printf("RAM Usage: %.2f\n"), $3/$2*100}'| awk '{print $3}'` with `awk '/Mem/{printf "%d", $3/$2*100}'` – accdias Apr 25 '21 at 19:04
  • Bash only understands integers, not floating-point numbers for comparisons, math, etc. You can use `${ramusage%.*}` to remove the decimal before comparing it. – Gordon Davisson Apr 25 '21 at 19:04
  • See also [BashFAQ #22](https://mywiki.wooledge.org/BashFAQ/022). – Charles Duffy Apr 25 '21 at 19:04
  • BTW, why are you chaining two `awk`s together like this? If you don't want the `RAM Usage:` printed, just take it out of the format string; there's no reason to have a second awk invocation. – Charles Duffy Apr 25 '21 at 19:08
  • if [ $ramusage -gt 80 2> /dev/null ]; then – GoldHaloWings Apr 25 '21 at 19:17
  • 1
    @GoldHaloWings That hides the error message, but doesn't fix the actual error. – Gordon Davisson Apr 25 '21 at 19:20
  • @GoldHaloWings, ...so if you do that, you _always_ have a test result of `false` (when the value is formatted as a floating-point number), no matter if the number is above or below 80. – Charles Duffy Apr 25 '21 at 19:22
  • iRamusage=$(sed 's/[.].*//' <<< "$ramusage") if [ $iRamusage -gt 80 ]; then – GoldHaloWings Apr 25 '21 at 19:37
  • 1
    Thank you guys for helping me out, now my script works by using the code @accdias Charles Duffy provided. To be honest, I'm still quite overwhelmed over the flow of information that I need to absorb. Many thanks to all of you, now I know the areas I need to improve especially to CharlesDuffy, Gordon Davisson, accdias and GoldHaloWings for taking your time and input in solving this small problem of mine. Cheers! – stillnoob Apr 26 '21 at 04:05

0 Answers0