Home > OS >  Bash Script "integer expression expected" , (floats in bash) replace part with awk
Bash Script "integer expression expected" , (floats in bash) replace part with awk

Time:11-20

I wrote a little bash-script to check my Memory-usage and warn me if it's to high.

now my problem is, that I would like to keep the floating-value instead of just cutting it away. but I'm not able to do it..

I would prefer awk over anything else as it's pre-installed on many systems and I already use it in the script.

#!/bin/bash
#define what values are too high (%)
inacceptableRAM="90"
#check RAM %
RAM=`free | grep Mem | awk '{print $3/$2 * 100.0}'`
#send Alarm for RAM
if [ $RAM -ge $inacceptableRAM ] ; then
   echo Alarm RAM usage is @$RAM"
fi

so how can I replace my if -ge using awk? I think it should look something like: awk ' $RAM >= $inacceptableRAM ' but what do I need to do to make it work inside the bash script?

CodePudding user response:

An alternative to awk is bc , something like:

#!/usr/bin/env bash

#define what values are too high (%)
inacceptableRAM="90"

#check RAM %
ram=$(free | awk '/Mem/{print $3/$2 * 100.0}')

#send Alarm for RAM
if (( $(bc <<< "$ram > $inacceptableRAM") )) ; then
   echo "Alarm RAM usage is @$ram"
fi

CodePudding user response:

Since you're comparing with an integer, you can just trim off the decimal part when comparing:

if [ "${RAM%.*}" -ge "$inacceptableRAM" ] ; then

If you want to do it entirely in awk, the only tricky thing is that you have to use -v var=value to convert the inacceptableRAM shell variable into an awk variable:

free | awk -v limit="$inacceptableRAM" '/Mem/ {ram=$3/$2*100; if (ram>=limit) print ram}'

Note that I'm using /Mem/ in the awk script to effectively replace the grep command. Piping from grep to awk is almost never necessary, since you can just do it all in awk.

Other recommendations: use $( ) instead of backticks for command substitutions, and use lower- or mixed-case variable names (e.g. ram instead of ram) to avoid accidentally using one of the many all-caps names that have special meanings.

CodePudding user response:

You're trying to do too much in shell. A shell is a tool to manipulate files and process and sequence calls to other tools. The tool that the guys who created shell also created for shell to call to manipulate text is awk:

#!/usr/bin/env bash

free |
awk '
    BEGIN {
        #define what values are too high (%)
        unacceptableRam = 90
    }
    /Mem/ {
        #check RAM %
        ram = ( $2 ? $3 / $2 * 100 : 0 )

        #send Alarm for RAM
        if ( ram >= unacceptableRam ) {
            print "Alarm RAM usage is @" ram
        }
    }
'
  • Related