Skip to content

Instantly share code, notes, and snippets.

@Ircama
Last active June 16, 2022 07:21
Show Gist options
  • Save Ircama/f51b09e8d350a487a778bd380c8dd67b to your computer and use it in GitHub Desktop.
Save Ircama/f51b09e8d350a487a778bd380c8dd67b to your computer and use it in GitHub Desktop.

Linux free command with percent

Introduction

This script is a simple and fast awk rewrite of the first two lines of the Linux free -wh command (with amount of memory fixed to mebibytes), calculating the percentage of the total for each value and running on Ubuntu or on the Raspberry Pi. It reads data from /proc/meminfo.

I developed this because free does not provide percentages.

Code

awk '$1=="MemTotal:" {total=$2};
$1=="MemFree:" {free=$2};
$1=="MemAvailable:" {available=$2};
$1=="Buffers:" {buffers=$2};
$1=="Cached:" {cached=$2};
$1=="Shmem:" {shmem=$2};
$1=="SReclaimable:" {sreclaimable=$2;
cache = cached+sreclaimable
used = total-free-buffers-cache
printf("               Total        Used        Free      Shared     Buffers       Cache   Available\n");
printf("Memory:  %9dMi %9dMi %9dMi %9dMi %9dMi %9dMi %9dMi\n",
    total/1024, used/1024, free/1024, shmem/1024, buffers/1024, cache/1024, available/1024);
printf("                     %10.1f%% %10.1f%% %10.1f%% %10.1f%% %10.1f%% %10.1f%%\n",
    used/total*100, free/total*100, shmem/total*100, buffers/total*100, cache/total*100, available/total*100);
exit}' /proc/meminfo

Output sample

               Total        Used        Free      Shared     Buffers       Cache   Available
Memory:        429Mi       193Mi        67Mi        53Mi        12Mi       156Mi       128Mi
                           45.1%       15.6%       12.4%        2.9%       36.4%       30.0%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment