get available memory in gb using single bash shell command - linux

following command returns available memory in kilobytes
cat /proc/meminfo | grep MemFree | awk '{ print $2 }'
can some one suggest single command to get the available memory in gb?

Just a slight modification to your own magical incantation:
awk '/MemFree/ { printf "%.3f \n", $2/1024/1024 }' /proc/meminfo
P.S.: Dear OP, if you find yourself invoking grep & awk in one line you're most likely doing it wrong ;} ... Same with invoking cat on a single file; that's hardly ever warranted.

Most simple is the following :
free -h
Following is the output Screenshot :
More details :
DESCRIPTION
free - displays the total amount of free and used physical and swap mem‐
ory in the system, as well as the buffers and caches used by the ker‐
nel. The information is gathered by parsing /proc/meminfo. The dis‐
played columns are:
total Total installed memory (MemTotal and SwapTotal in /proc/meminfo)
used Used memory (calculated as total - free - buffers - cache)
free Unused memory (MemFree and SwapFree in /proc/meminfo)
shared Memory used (mostly) by tmpfs (Shmem in /proc/meminfo, available
on kernels 2.6.32, displayed as zero if not available)
buffers
Memory used by kernel buffers (Buffers in /proc/meminfo)
cache Memory used by the page cache and slabs (Cached and Slab in
/proc/meminfo)
buff/cache
Sum of buffers and cache
available
Estimation of how much memory is available for starting new
applications, without swapping. Unlike the data provided by the
cache or free fields, this field takes into account page cache
and also that not all reclaimable memory slabs will be reclaimed
due to items being in use (MemAvailable in /proc/meminfo, avail‐
able on kernels 3.14, emulated on kernels 2.6.27+, otherwise the
same as free)

freemem_in_gb () {
read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
bc <<< "scale=3;${freemem}/1024/1024"
}
Please notice that scale=3 can be changed to some other value, for a better precision.
So, for example one could write a function that will take a precision argument, like so:
freemem_in_gb () {
prec=$1;
read -r _ freemem _ <<< "$(grep --fixed-strings 'MemFree' /proc/meminfo)"
bc <<< "scale=${prec:-3};${freemem}/1024/1024"
}
Which will take (or use 3 as a default value) and pass a precision argument to bc's scale option
Usage example:
$ freemem_in_gb
5.524
$ freemem_in_gb 7
5.5115814
EDIT
Thanks for #Stephen P and #Etan Reisner for leaving a comment and improving this answer.
Code edited accordingly.
grep's long option --fixed-strings is used purposely instead of -F or fgrep for explanatory reasons.

Yet another way:
expr $(sed -n '/^MemTotal:/ s/[^[:digit:]]//gp' /proc/meminfo) / 1024 / 1024
Also a bit shorter:
expr $(sed -n '/^MemTotal:/ s/[^0-9]//gp' /proc/meminfo) / 1024 / 1024
And if you like bc and precision that much:
bc <<< "scale=2; $(sed -n '/^MemTotal:/ s/[^[:digit:]]//gp' /proc/meminfo) / 1024 / 1024 "

If you have python, you can do it this way:
To get total available memory:
python -c "import os;print(int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3)))"
In this example, I used round to round to the nearest GB. You can make it into a shell function like so:
get_mem(){
MEM=$(python -c "import os;print(int(round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024.0**3)))")
echo $MEM
}
To get free and used memory check out psutil here.

Whilst I agree that dividing by 1024 should be more correct, I find on my various cloud and physical servers, this gives neater output:
free -m | awk '/^Mem:/{printf("%.1fGb\n",$2/1000)}'

Related

buff/cache gets filled, how to clear it AZURE VM

my RAM got filled completely, and the buff/cache occupied all the memory pl z do let me know how to make it clear when I run the command free -m I get this output,
this is a Linux VM made on azure for WordPress bitnami
$ free -m
total used free shared buff/cache available
Mem: 64320 19319 3164 115 41837 44168
Swap: 0
image
I tried to reproduce the same in my environment I got some buff/cache like below.
To clear the buff/cache try to use the below command.
Every Linux has three options to clear cache
First - clear page cache only
echo 1 > /proc/sys/vm/drop_caches
Second - clear dentries and inodes
echo 2 > /proc/sys/vm/drop_caches
Third - clear page cache and dentries and inodes
echo 3 > /proc/sys/vm/drop_caches
When I try to run this above script, there is 912M of total RAM, and 144M as used. And before I have 352M as free after exciting the script my buff/cache were reduced from 415 to 58 and free Ram increased upto 708M
Reference:
Clear RAM Memory Cache, Buffer, and Swap Space on Linux Credits by Arpit-saini

Differences in showing disk usage percentage

I'm using Arch Linux.
When I run df -T command it gives me this:
Filesystem Type 1K-blocks Used Available Use% Mounted on
/dev/sda3 ext4 930449240 750685092 132430124 86% /home
As it can be seen, the number on "Use%" column displays 86 while through echo $(awk "BEGIN {printf \"%.3f\n\", 771793804 * 100 / 930449240}") I get 82.95.
What do you think is causing the difference in numbers and which one is the more reliable one?

shm_unlink from the shell?

I have a program that creates a shared memory object with shm_open that I'm working on. It tries to release the object with shm_unlink, but sometimes a programming error will cause it to crash before it can make that call. In that case, I need to unlink the shared memory object "by hand," and I'd like to be able to do it in a normal shell, without writing any C code -- i.e. with normal Linux utilities.
Can it be done? This question seems to say that using unlink(1) on /dev/shm/path_passed_to_shm_open, but the manpages aren't clear.
Unlinking the file in /dev/shm will delete the shared memory object if no other process has the object mapped.
Unlike SYSV shared memory, which is implemented in the Kernel, POSIX shared memory objects are simply "files in disguise".
When you call shm_open and mmap, you can see the following in the process process map (using pmap -X):
Address Perm Offset Device Inode Mapping
b7737000 r--s 00000000 00:0d 2267945 test_object
The device major and minor number correspond to the tmpfs mounted at /dev/shm (some systems mount this at /run, and then symlink /dev/shm to /run/shm).
A listing of the folder will show the same inode number:
$ ls -li /dev/shm/
2267945 -rw------- 1 mikel mikel 1 Apr 14 13:36 test_object
Like any other inode, the space will be freed when all references are removed. If we close the only program referencing this we see:
$ cat /proc/meminfo | grep Shmem
Shmem: 700 kB
Once we remove the last reference (created in /dev/shm), the space will be freed:
$ rm /dev/shm/test_object
$ cat /proc/meminfo | grep Shmem
Shmem: 696 kB
If you're curious, you can look at the corresponding files in the glibc sources. shm_directory.c and shm_directory.h generate the filename as /dev/your_shm_name. The implementations shm_open and shm_unlink simply open and unlink this file. So it should be easy to see that rm /dev/shm/your_shm_name performs the same operation,

How to get the total memory of a process which fork many children in linux with shell?

http daemon for example:
I use ps aux|grep httpd|grep -v grep:
USER PID RSS COMMAND
root 14347 3220 /usr/sbin/httpd
apache 14348 2400 /usr/sbin/httpd
apache 14349 2400 /usr/sbin/httpd
apache 14350 2400 /usr/sbin/httpd
I can simple accumulate the RSS fields to get total memory usage of [httpd]. 3220+2400+2400+2400 = 10420
But i know, child processes have shared memory. There are some redundant computing here. Actually the total memory usage size may less than 10420.
My question is how to get the actually memory usage.
If you need to get the actual memory usage, you need to run it within a profiler like Valgrind.
reference
http://kratos-wiki.cimne.upc.edu/index.php/Checking_memory_use_with_Valgrind
Valgrind is probably your most exact choice, but can be a bit awkward to use, and is not reasonable for a production system because of performance (virtually none).
Smem (homepage) (manpage) is a less complicated alternative. PSS process set size is what you're looking for.
I have used the following command, with Chrome:
ps aux | grep chrome | grep -v grep | awk '{s+=$5} END {print s}'
Note that $5 may actually vary, depending on how ps aux actually displays its output. This may or may not be useful to you and also displays the total usage in bytes.

How can the physical RAM size be determined in Linux programatically?

On the command line this can be found out using the 'free' utility and 'cat /proc/meminfo'.
What would be the different ways to find out the physical RAM size in Linux programatically from a :
Userspace Application
Kernel Module
What API calls are available ?
#include <unistd.h>
long long physical_mem_bytes = (long long) sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);
Other than the command line ulimit, I don't know of a way of finding maximum memory for an individual process.
Programmatically, Linux won't tell you the actual physical size. Instead you should read this info from SMBIOS with, e.g.,
sudo dmidecode -t memory | fgrep -ie 'size:'
This will give you results like the following (from a box with 4 RAM banks, only 2 installed):
Maximum Memory Module Size: 16384 MB
Maximum Total Memory Size: 65536 MB
Installed Size: 2048 MB (Single-bank Connection)
Enabled Size: 2048 MB (Single-bank Connection)
Installed Size: Not Installed
Enabled Size: Not Installed
Installed Size: 2048 MB (Single-bank Connection)
Enabled Size: 2048 MB (Single-bank Connection)
Installed Size: Not Installed
Enabled Size: Not Installed
Size: 2048 MB
Size: No Module Installed
Size: 2048 MB
Size: No Module Installed
Add the reported sizes (or Enabled Sizes, but some BIOSes empirically don't report that) to get (in this case) 4096 MB. (Extra points for code that automates the parsing and arithmetic, but you can probably do that in your head nearly as reliably.)
To check your computation, run
fgrep -e 'MemTotal:' /proc/meminfo
The value reported by /proc/meminfo should not be more than the value you compute from dmidecode. In this case, empirically I get
MemTotal: 3988616 kB
cat /proc/meminfo
specifically from memory, I got this result from what Jared said
sudo dmidecode -t memory
there you can read the specs for each individual memory slot, so you will read something like 2048MB, in my case I have 2 of these being 4gb, despite my non PAE kernel only shows about 3.3gb and all other applications wont say the real physical memory, only dmidecode, thx!

Resources