Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
Sometimes we want to know the memory usage of our Linux system. In this tutorial, we’ll see how to use the free command-line utility to do just that.
The free command is a Linux tool that shows the current RAM and swap space usage:
$ free
total used free shared buff/cache available
Mem: 32882588 4418516 26725724 437164 1738348 27589116
Swap: 2097148 0 2097148
Let’s look at what each column in our output means:
The free command, by default, displays all the values in KB, which can be a bit uncomfortable to read, but we can use the -h option to display the numbers in a more readable format:
$ free -h
total used free shared buff/cache available
Mem: 31G 6.2G 23G 541M 1.9G 24G
Swap: 1.5G 0B 1.5G
To display the values expressed in megabytes we can use the -m option:
$ free -m
total used free shared buff/cache available
Mem: 32111 6200 23000 541 1900 24000
Swap: 1500 0 1500
Likewise, we can also show the values expressed in gigabytes using the -g option:
$ free -g
total used free shared buff/cache available
Mem: 31 6 23 0 1 24
Swap: 1 0 1
By default, the values are expressed by the power of 1024, but if we want to display the value expressed by the power of 1000, we can use the –si option:
$ free -h --si
total used free shared buff/cache available
Mem: 32G 6.3G 22G 553M 1.8G 25G
Swap: 1.5G 0B 1.5G
If we want to know the amount of RAM and swap used/free memory combined we can use the -t option:
$ free -h -t
total used free shared buff/cache available
Mem: 31G 13G 9.8G 1.1G 8.3G 16G
Swap: 1.5G 0B 0B
Total: 32.5G 13G 11.3G
We can also use free to show memory usage in realtime.
Let’s use the -s option followed by the number of seconds we want between each display:
$ free -h -s 2
total used free shared buff/cache available
Mem: 31G 6.2G 23G 541M 1.9G 24G
Swap: 1.5G 0B 1.5G
total used free shared buff/cache available
Mem: 31G 6.2G 23G 541M 1.9G 24G
Swap: 1.5G 0B 1.5G
total used free shared buff/cache available
Mem: 31G 6.2G 23G 541M 1.9G 24G
Swap: 1.5G 0B 1.5G
In this example, we’ll get the statistics every 2 seconds.
Sometimes we need to log the memory usage for a long time. In this case, a small Bash script can be useful.
We can execute the free command and the date command together and redirect the result to a log file:
while true; do date >> memory.log; free >> memory.log; sleep 1; done
This one-line script will write to a log file the date and the memory usage every second. Of course, we can tweak the number after sleep to change the log frequency.
In this quick tutorial, we learned how to use the free command to display and log the system memory usage. This won’t stop us from having memory problems but will help us diagnose them if we do.