Skip to content

Commit dc81200

Browse files
committed
Implement memory calculation for Linux systems
1 parent 21a3fd6 commit dc81200

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

scripts/helpers.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ is_osx() {
2020
[ $(uname) == "Darwin" ]
2121
}
2222

23+
is_linux(){
24+
[ $(uname -s) == "Linux" ]
25+
}
26+
27+
2328
command_exists() {
2429
local command="$1"
2530
type "$command" >/dev/null 2>&1

scripts/mem.sh

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,9 @@ print_mem() {
4444
local size_format
4545

4646
if is_osx; then
47+
mem_usage=$(get_mem_usage_linux)
48+
elif is_linux; then
4749
mem_usage=$(get_mem_usage_osx)
48-
else
49-
# TODO: implement memory calculation for linux
50-
mem_usage="TODO"
5150
fi
5251

5352
# get_mem_usage* function returns values in KiB
@@ -87,8 +86,6 @@ print_mem() {
8786
# Calculate colors for mem and swap
8887
local mem_color=$(get_mem_color "$mem_pused")
8988
local swap_color=$(get_swap_color "$swap_pused")
90-
91-
echo $mem_view_tmpl;
9289

9390
local mem_view="$mem_view_tmpl"
9491
mem_view="${mem_view//'#{mem.used}'/$(printf "$size_format" "$mem_used" "$size_unit")}"
@@ -144,6 +141,37 @@ get_mem_usage_osx(){
144141
printf "%s %s %s" "$free_used" "$swap_free" "$swap_used"
145142
}
146143

144+
145+
# Method #1. Sum up free+buffers+cached, treat it as "available" memory, assuming buff+cache can be reclaimed. Note, that this assumption is not 100% correct, buff+cache most likely cannot be 100% reclaimed, but this is how memory calculation is used to be done on Linux
146+
147+
# Method #2. If "MemAvailable" is provided by system, use it. This is more correct method, because we're not relying on fragile "free+buffer+cache" equation.
148+
149+
# See: Interpreting /proc/meminfo and free output for Red Hat Enterprise Linux 5, 6 and 7 - Red Hat Customer Portal - https://access.redhat.com/solutions/406773
150+
151+
# See: kernel/git/torvalds/linux.git - /proc/meminfo: provide estimated available memory - https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
152+
get_mem_usage_linux(){
153+
local mem_free_used=$( </proc/meminfo awk '
154+
BEGIN { total=0; free=0; }
155+
/MemTotal:/ { total=$2; }
156+
157+
/MemFree:/ { free+=$2; }
158+
/Buffers:/ { free+=$2; }
159+
/Cached:/ { free+=$2; }
160+
161+
/MemAvailable:/ { free=$2; exit;}
162+
END { print free, total-free }
163+
')
164+
165+
local swap_free_used=$( </proc/meminfo awk '
166+
BEGIN { total=0; free=0; }
167+
/SwapTotal:/ { total=$2; }
168+
/SwapFree:/ { free=$2; }
169+
END { print free, total-free }
170+
')
171+
172+
printf "%s %s" "$mem_free_used" "$swap_free_used"
173+
}
174+
147175
main() {
148176
print_mem
149177
}

0 commit comments

Comments
 (0)