-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_check_memory_usage.sh
More file actions
executable file
·83 lines (72 loc) · 1.96 KB
/
linux_check_memory_usage.sh
File metadata and controls
executable file
·83 lines (72 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/bin/bash
#
# Check Memory Usage [Linux]
#
# Supports:
# Linux-All
#
# Category:
# Memory
#
# License:
# AGPLv3
#
# Author:
# Charlie Powell <cdp1337@veraciousnetwork.com>
#
# Syntax:
# --threshold=<integer> - Threshold of memory used before an error is dispatched DEFAULT=20
#
# Changelog:
# 20250204 - Initial version
# Parse arguments
THRESHOLD="20"
while [ "$#" -gt 0 ]; do
case "$1" in
--threshold=*|--threshold)
[ "$1" == "--threshold" ] && shift 1 && THRESHOLD="$1" || THRESHOLD="${1#*=}"
[ "${THRESHOLD:0:1}" == "'" ] && [ "${THRESHOLD:0-1}" == "'" ] && THRESHOLD="${THRESHOLD:1:-1}"
[ "${THRESHOLD:0:1}" == '"' ] && [ "${THRESHOLD:0-1}" == '"' ] && THRESHOLD="${THRESHOLD:1:-1}"
;;
*) echo "Unknown argument: $1" >&2; usage;;
esac
shift 1
done
MEM="$(free -m | grep Mem)"
TOTAL="$(echo $MEM | awk '{print $2}')"
USED="$(echo $MEM | awk '{print $3}')"
FREE="$(echo $MEM | awk '{print $4}')"
SHARED="$(echo $MEM | awk '{print $5}')"
BUFF="$(echo $MEM | awk '{print $6}')"
AVAIL="$(echo $MEM | awk '{print $7}')"
PCENT=$(echo "scale=2; 100 - $USED / $TOTAL * 100" | bc)
# Print used and free to stderr for reference
if [ $USED -le 4096 ]; then
echo "Used Memory: $(echo "$USED")MB" >&2
else
echo "Used Memory: $(echo "$USED / 1024" | bc)GB" >&2
fi
if [ $FREE -le 4096 ]; then
echo "Free/Unallocated Memory: $(echo "$FREE")MB" >&2
else
echo "Free/Unallocated Memory: $(echo "$FREE / 1024" | bc)GB" >&2
fi
if [ $SHARED -le 4096 ]; then
echo "Free/Shared Memory: $(echo "$SHARED")MB" >&2
else
echo "Free/Shared Memory: $(echo "$SHARED / 1024" | bc)GB" >&2
fi
if [ $BUFF -le 4096 ]; then
echo "Free/Buffer Memory: $(echo "$BUFF")MB" >&2
else
echo "Free/Buffer Memory: $(echo "$BUFF / 1024" | bc)GB" >&2
fi
echo "Percent Free: $PCENT%" >&2
# Print percent free to stdout for logging / tracking
echo $PCENT
# Return status based if percentage free is below defined threshold
if [ $(echo "$PCENT < $THRESHOLD" | bc) -eq 1 ]; then
exit 1
else
exit 0
fi