Skip to content

Check-memory-percent.sh not returning correct values for Linux systems #82

Description

@tfalkowski-nsidc

FWIW, I am using both Ubuntu 16/18 and CentOS 7 systems.

So near as I can tell this issues is caused by an incorrect parsing of the values returned by the free -m command as well as not calculating the free memory correctly.

Using the following output from the free -m command as an example,

                total        used        free      shared  buff/cache   available
     Mem:        3951        2915         224          32         812         731
     Swap:       1951         404        1547

The following code does not make much sense:

elif [ $os = "Linux" ]; then
  # Get total memory available on machine
  TotalMem=$(free -m | grep Mem | awk '{ print $2 }')
  # Determine amount of free memory on the machine
  set -o pipefail
  FreeMem=$(free -m | grep buffers/cache | awk '{ print $4 }')
  if [ $? -ne 0 ]; then
    FreeMem=$(free -m | grep Mem | awk '{ print $7 }')
  fi
fi

The first issue is where the code attempts to set the value for FreeMem.

This command:

FreeMem=$(free -m | grep buffers/cache | awk '{ print $4 }')
# does not actually return anything which causes the program bail out to the line after the "if [ $? -ne 0 ]; then" statement

# It probably ought to  be:
FreeMem$(free -m | grep Mem | awk '{ print $6 }')

However, this is also an issue as is it not the full picture of the free memory on the system.

FreeMem should be defined as:

Free Memory = Free + Buffers + Cached

So, using the the example data above we would have
Free Memory = Free (224 MB) + Buffers & Cache (812) = 1,036 MB.

A possible solution might look something like this:

elif [ $os = "Linux" ]; then`
  # Get total memory available on machine
  TotalMem=$(free -m | grep Mem | awk '{ print $2 }')
  # Determine amount of free memory on the machine
  set -o pipefail
  FreeMem=$(free -m | grep Mem | awk '{ print $4 }')
  BuffCache=$(free -m | grep Mem | awk '{ print $6 }')
 if [ $? -ne 0 ]; then
   UsedMem=$(free -m | grep Mem | awk '{ print $3 }')
 fi
fi
# Get percentage of free memory
TotalFree=$(($FreeMem+$BuffCache))
FreePer=$(awk -v total="$TotalMem" -v free="$TotalFree" 'BEGIN { printf("%-10f\n", (free / total) * 100) }' | cut -d. -f1)

Thank you for your effort on this project,
-Thomas

EDIT BY @majormoses: used triple backticks to form code blocks so its easier to read

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions