Created
September 12, 2025 00:31
-
-
Save henri/4db05af2a6efccc884864d17800aa7e6 to your computer and use it in GitHub Desktop.
memory_monitor.bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # memory monitor script | |
| # Henri Shustak | |
| # (C) 2022 GNU GPL v3 or later | |
| # basic path setup (good for most systems) | |
| PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin | |
| # settings (this could be improved to use percentages)... | |
| memory_check_interval=520 # seconds | |
| memory_low_threshold=1500 # megabytes | |
| swap_low_threshold=9000 # megabyes | |
| email_sender="[email protected]" | |
| email_alerts="[email protected]" | |
| memory_log_file="/tmp/memory_free.log" | |
| # create the log file | |
| touch $memory_log_file | |
| chmod 755 $memory_log_file | |
| while true ; do | |
| # check free memory | |
| current_free_memory=$(free -m | grep "^Mem" | sed 's/\s\+/ /g' | cut -d " " -f 7) | |
| if [[ $current_free_memory -le $memory_low_threshold ]] ; then | |
| echo "WARNING! Low Swap Detected : Available Memory : $current_free_memory MB" | mailx -aFrom:"Memory Monitor <$email_sender>" -s "$(hostname) : Low Memory" $email_alerts | |
| fi | |
| # check free swap | |
| current_free_swap=$(free -m | grep "^Swap" | sed 's/\s\+/ /g' | cut -d " " -f 4) | |
| if [[ $current_free_swap -le $swap_low_threshold ]] ; then | |
| echo "WARNING! Low Swap Detected : Available Swap : $current_free_swap MB" | mailx -aFrom:"Memory Monitor <$email_sender>" -r $email_sender -s "$(hostname) : Low Swap" $email_alerts | |
| fi | |
| # log free memory to /tmp/free_memory.log | |
| echo "$(date) | current_free_memory : ${current_free_memory} MB | current_free_swap : ${current_free_swap} MB " >> ${memory_log_file} | |
| # hang tight for next check | |
| sleep $memory_check_interval | |
| done | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [Unit] | |
| Description=Memory Monitoring Script | |
| After=network.target | |
| [Service] | |
| Type=simple | |
| ExecStart=/path/to/memory_monitor.bash | |
| [Install] | |
| WantedBy=multi-user.target |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment