Warning when available RAM approaches zero












6















This is a follow-up to Memory limiting solutions for greedy applications that can crash OS?: ulimit and cgroups are not user friendly, and besides, wouldn't work with applications that spawn separate processes, such as Chrome/Chromium for each new (group of) tabs.



The simple and effective solution, used by Windows 7 actually, is to warn the user that the OS is running low on memory. This simple warning pop-up has prevented me from having any low-memory-caused system freeze in Windows, while I kept running into them on Ubuntu distros that I was testing live (where the RAM-mounted disk would eat up 2GB alone).



So, is there some way to automatically warn the user that the available RAM is nearing zero, without the user having to keep an eye on some memory monitoring gadget? Surely Conky could be configured to do that?










share|improve this question




















  • 1





    Four years later, looks like periodically checking free -m is the way to go.

    – Dan Dascalescu
    Oct 7 '16 at 6:29
















6















This is a follow-up to Memory limiting solutions for greedy applications that can crash OS?: ulimit and cgroups are not user friendly, and besides, wouldn't work with applications that spawn separate processes, such as Chrome/Chromium for each new (group of) tabs.



The simple and effective solution, used by Windows 7 actually, is to warn the user that the OS is running low on memory. This simple warning pop-up has prevented me from having any low-memory-caused system freeze in Windows, while I kept running into them on Ubuntu distros that I was testing live (where the RAM-mounted disk would eat up 2GB alone).



So, is there some way to automatically warn the user that the available RAM is nearing zero, without the user having to keep an eye on some memory monitoring gadget? Surely Conky could be configured to do that?










share|improve this question




















  • 1





    Four years later, looks like periodically checking free -m is the way to go.

    – Dan Dascalescu
    Oct 7 '16 at 6:29














6












6








6


4






This is a follow-up to Memory limiting solutions for greedy applications that can crash OS?: ulimit and cgroups are not user friendly, and besides, wouldn't work with applications that spawn separate processes, such as Chrome/Chromium for each new (group of) tabs.



The simple and effective solution, used by Windows 7 actually, is to warn the user that the OS is running low on memory. This simple warning pop-up has prevented me from having any low-memory-caused system freeze in Windows, while I kept running into them on Ubuntu distros that I was testing live (where the RAM-mounted disk would eat up 2GB alone).



So, is there some way to automatically warn the user that the available RAM is nearing zero, without the user having to keep an eye on some memory monitoring gadget? Surely Conky could be configured to do that?










share|improve this question
















This is a follow-up to Memory limiting solutions for greedy applications that can crash OS?: ulimit and cgroups are not user friendly, and besides, wouldn't work with applications that spawn separate processes, such as Chrome/Chromium for each new (group of) tabs.



The simple and effective solution, used by Windows 7 actually, is to warn the user that the OS is running low on memory. This simple warning pop-up has prevented me from having any low-memory-caused system freeze in Windows, while I kept running into them on Ubuntu distros that I was testing live (where the RAM-mounted disk would eat up 2GB alone).



So, is there some way to automatically warn the user that the available RAM is nearing zero, without the user having to keep an eye on some memory monitoring gadget? Surely Conky could be configured to do that?







ram memory-usage






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 13 '17 at 12:24









Community

1




1










asked Dec 30 '12 at 7:25









Dan DascalescuDan Dascalescu

1,12321637




1,12321637








  • 1





    Four years later, looks like periodically checking free -m is the way to go.

    – Dan Dascalescu
    Oct 7 '16 at 6:29














  • 1





    Four years later, looks like periodically checking free -m is the way to go.

    – Dan Dascalescu
    Oct 7 '16 at 6:29








1




1





Four years later, looks like periodically checking free -m is the way to go.

– Dan Dascalescu
Oct 7 '16 at 6:29





Four years later, looks like periodically checking free -m is the way to go.

– Dan Dascalescu
Oct 7 '16 at 6:29










5 Answers
5






active

oldest

votes


















3














Check these scripts:
Need application/script alerting when system memory is running out



#!/bin/bash

#Minimum available memory limit, MB
THRESHOLD=400

#Check time interval, sec
INTERVAL=30

while :
do

free=$(free -m|awk '/^Mem:/{print $4}')
buffers=$(free -m|awk '/^Mem:/{print $6}')
cached=$(free -m|awk '/^Mem:/{print $7}')
available=$(free -m | awk '/^-/+/{print $4}')

message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""

if [ $available -lt $THRESHOLD ]
then
notify-send "Memory is running out!" "$message"
fi

echo $message

sleep $INTERVAL

done


PHP:



#!/usr/bin/php
<?php
$alert_percent=($argc>1)?(int)$argv[1]:90;
//$interval=($argc>2):(int)$argv[2]:25;



//while(true)
//{
exec("free",$free);

$free=implode(' ',$free);
preg_match_all("/(?<=s)d+/",$free,$match);

list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];

$used_mem-=($buffered_mem+$cached_mem);

$percent_used=(int)(($used_mem*100)/$total_mem);

if($percent_used>$alert_percent)
exec("notify-send 'Low Memory: $percent_used% used'");

//sleep($interval);
//}
exit();
?>





share|improve this answer





















  • 1





    The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

    – morsch
    Aug 15 '16 at 21:50











  • If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

    – Freddi Schiller
    May 19 '17 at 10:22





















1














Another script that I wrote for this purpose:



#!/bin/bash
# Copyright 2019, Mikko Rantalainen
# License: MIT X License

# Minimum available memory until warning, default to 10% of total RAM (MiB)
THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
INTERVAL=60s

echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."

while true; do
meminfo=$(cat /proc/meminfo)
free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
if test -z "$available"; then
message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
notify-send "Error while monitoring low memory" "$message"
echo "$message" 1>&2
exit 1
fi

message="Available: $available MiB
Free: $free MiB
Maybe usable: $usable MiB"

if [ "$available" -lt "$THRESHOLD" ]
then
notify-send -u critical "Low memory warning" "$message"
echo "Low memory warning:"
echo "$message"
fi

#echo "DEBUG: $message"
sleep $INTERVAL
done





share|improve this answer


























  • Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

    – Dan Dascalescu
    Feb 13 at 8:36













  • Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

    – Mikko Rantalainen
    Feb 13 at 14:11



















0














Updated version of the script which works with free from procps-ng 3.3.10



#!/bin/bash

#Minimum available memory limit, MB
THRESHOLD=400

#Check time interval, sec
INTERVAL=30

while :
do
free_out=$(free -w -m)
available=$(awk '/^Mem:/{print $8}' <<<$free_out)

if (( $available < $THRESHOLD ))
then
notify-send -u critical "Memory is running out!" "Available memory is $available MiB"
echo "Warning - available memory is $available MiB"
fi

cat <<<$free_out
sleep $INTERVAL
done





share|improve this answer































    0














    Updated above script to also add details on top 3 memory-hungry processes.
    See at https://github.com/romanmelko/ubuntu-low-mem-popup



    Here is the script itself:



    #!/usr/bin/env bash

    set -o errexit
    set -o pipefail
    set -o nounset

    # If the language is not English, free will output localized text and parsing fails
    LANG=en_US.UTF-8

    THRESHOLD=500
    INTERVAL=300
    POPUP_DELAY=999999

    # sleep some time so the shell starts properly
    sleep 60

    while :
    do
    available=$(free -mw | awk '/^Mem:/{print $8}')
    if [ $available -lt $THRESHOLD ]; then
    title="Low memory! $available MB available"
    message=$(top -bo %MEM -n 1 | grep -A 3 PID | awk '{print $(NF - 6) " t" $(NF)}')
    # KDE Plasma notifier
    kdialog --title "$title" --passivepopup "$message" $POPUP_DELAY
    # use the following command if you are not using KDE Plasma, comment the line above and uncomment the line below
    # please note that timeout for notify-send is represented in milliseconds
    # notify-send -u critical "$title" "$message" -t $POPUP_DELAY
    fi
    sleep $INTERVAL
    done





    share|improve this answer










    New contributor




    Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















    • Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

      – Marc Vanhoomissen
      Mar 6 at 14:07



















    0














    Variant using percentages and displays notification when called by cron:



    #!/usr/bin/env bash

    eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ | tr '' 'n')";

    FREE_THRESHOLD=5

    free_output=$(free)

    mem_total=$(awk '/^Mem:/{print $2}' <<< $free_output)
    mem_free=$(awk '/^Mem:/{print $4}' <<< $free_output)
    mem_free_m=$(bc <<< "scale=1; $mem_free/1024")
    percent_free=$(bc <<< "scale=1; $mem_free*100 /$mem_total")
    should_warn=$(bc <<< "$percent_free < $FREE_THRESHOLD")

    if (( $should_warn )); then
    notify-send "Memory warning - only $percent_free% ($mem_free_m MB) free"
    else
    echo "Memory OK - $percent_free% ($mem_free_m MB) free"
    fi





    share|improve this answer








    New contributor




    lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




















      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "89"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f234292%2fwarning-when-available-ram-approaches-zero%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Check these scripts:
      Need application/script alerting when system memory is running out



      #!/bin/bash

      #Minimum available memory limit, MB
      THRESHOLD=400

      #Check time interval, sec
      INTERVAL=30

      while :
      do

      free=$(free -m|awk '/^Mem:/{print $4}')
      buffers=$(free -m|awk '/^Mem:/{print $6}')
      cached=$(free -m|awk '/^Mem:/{print $7}')
      available=$(free -m | awk '/^-/+/{print $4}')

      message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""

      if [ $available -lt $THRESHOLD ]
      then
      notify-send "Memory is running out!" "$message"
      fi

      echo $message

      sleep $INTERVAL

      done


      PHP:



      #!/usr/bin/php
      <?php
      $alert_percent=($argc>1)?(int)$argv[1]:90;
      //$interval=($argc>2):(int)$argv[2]:25;



      //while(true)
      //{
      exec("free",$free);

      $free=implode(' ',$free);
      preg_match_all("/(?<=s)d+/",$free,$match);

      list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];

      $used_mem-=($buffered_mem+$cached_mem);

      $percent_used=(int)(($used_mem*100)/$total_mem);

      if($percent_used>$alert_percent)
      exec("notify-send 'Low Memory: $percent_used% used'");

      //sleep($interval);
      //}
      exit();
      ?>





      share|improve this answer





















      • 1





        The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

        – morsch
        Aug 15 '16 at 21:50











      • If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

        – Freddi Schiller
        May 19 '17 at 10:22


















      3














      Check these scripts:
      Need application/script alerting when system memory is running out



      #!/bin/bash

      #Minimum available memory limit, MB
      THRESHOLD=400

      #Check time interval, sec
      INTERVAL=30

      while :
      do

      free=$(free -m|awk '/^Mem:/{print $4}')
      buffers=$(free -m|awk '/^Mem:/{print $6}')
      cached=$(free -m|awk '/^Mem:/{print $7}')
      available=$(free -m | awk '/^-/+/{print $4}')

      message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""

      if [ $available -lt $THRESHOLD ]
      then
      notify-send "Memory is running out!" "$message"
      fi

      echo $message

      sleep $INTERVAL

      done


      PHP:



      #!/usr/bin/php
      <?php
      $alert_percent=($argc>1)?(int)$argv[1]:90;
      //$interval=($argc>2):(int)$argv[2]:25;



      //while(true)
      //{
      exec("free",$free);

      $free=implode(' ',$free);
      preg_match_all("/(?<=s)d+/",$free,$match);

      list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];

      $used_mem-=($buffered_mem+$cached_mem);

      $percent_used=(int)(($used_mem*100)/$total_mem);

      if($percent_used>$alert_percent)
      exec("notify-send 'Low Memory: $percent_used% used'");

      //sleep($interval);
      //}
      exit();
      ?>





      share|improve this answer





















      • 1





        The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

        – morsch
        Aug 15 '16 at 21:50











      • If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

        – Freddi Schiller
        May 19 '17 at 10:22
















      3












      3








      3







      Check these scripts:
      Need application/script alerting when system memory is running out



      #!/bin/bash

      #Minimum available memory limit, MB
      THRESHOLD=400

      #Check time interval, sec
      INTERVAL=30

      while :
      do

      free=$(free -m|awk '/^Mem:/{print $4}')
      buffers=$(free -m|awk '/^Mem:/{print $6}')
      cached=$(free -m|awk '/^Mem:/{print $7}')
      available=$(free -m | awk '/^-/+/{print $4}')

      message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""

      if [ $available -lt $THRESHOLD ]
      then
      notify-send "Memory is running out!" "$message"
      fi

      echo $message

      sleep $INTERVAL

      done


      PHP:



      #!/usr/bin/php
      <?php
      $alert_percent=($argc>1)?(int)$argv[1]:90;
      //$interval=($argc>2):(int)$argv[2]:25;



      //while(true)
      //{
      exec("free",$free);

      $free=implode(' ',$free);
      preg_match_all("/(?<=s)d+/",$free,$match);

      list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];

      $used_mem-=($buffered_mem+$cached_mem);

      $percent_used=(int)(($used_mem*100)/$total_mem);

      if($percent_used>$alert_percent)
      exec("notify-send 'Low Memory: $percent_used% used'");

      //sleep($interval);
      //}
      exit();
      ?>





      share|improve this answer















      Check these scripts:
      Need application/script alerting when system memory is running out



      #!/bin/bash

      #Minimum available memory limit, MB
      THRESHOLD=400

      #Check time interval, sec
      INTERVAL=30

      while :
      do

      free=$(free -m|awk '/^Mem:/{print $4}')
      buffers=$(free -m|awk '/^Mem:/{print $6}')
      cached=$(free -m|awk '/^Mem:/{print $7}')
      available=$(free -m | awk '/^-/+/{print $4}')

      message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""

      if [ $available -lt $THRESHOLD ]
      then
      notify-send "Memory is running out!" "$message"
      fi

      echo $message

      sleep $INTERVAL

      done


      PHP:



      #!/usr/bin/php
      <?php
      $alert_percent=($argc>1)?(int)$argv[1]:90;
      //$interval=($argc>2):(int)$argv[2]:25;



      //while(true)
      //{
      exec("free",$free);

      $free=implode(' ',$free);
      preg_match_all("/(?<=s)d+/",$free,$match);

      list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];

      $used_mem-=($buffered_mem+$cached_mem);

      $percent_used=(int)(($used_mem*100)/$total_mem);

      if($percent_used>$alert_percent)
      exec("notify-send 'Low Memory: $percent_used% used'");

      //sleep($interval);
      //}
      exit();
      ?>






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Apr 13 '17 at 12:23









      Community

      1




      1










      answered Sep 17 '13 at 19:11









      StandardSpecificationStandardSpecification

      1713




      1713








      • 1





        The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

        – morsch
        Aug 15 '16 at 21:50











      • If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

        – Freddi Schiller
        May 19 '17 at 10:22
















      • 1





        The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

        – morsch
        Aug 15 '16 at 21:50











      • If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

        – Freddi Schiller
        May 19 '17 at 10:22










      1




      1





      The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

      – morsch
      Aug 15 '16 at 21:50





      The script works with small adaptations (I just used available=$(free -m | grep Mem | awk '{print $7}')). To make notify-send work with cron, refer to anmolsinghjaggi.wordpress.com/2016/05/11/…

      – morsch
      Aug 15 '16 at 21:50













      If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

      – Freddi Schiller
      May 19 '17 at 10:22







      If the language is not English, free will output localized text and parsing fails. Then add LANG=en_US.UTF-8 at the beginnning of the bash script.

      – Freddi Schiller
      May 19 '17 at 10:22















      1














      Another script that I wrote for this purpose:



      #!/bin/bash
      # Copyright 2019, Mikko Rantalainen
      # License: MIT X License

      # Minimum available memory until warning, default to 10% of total RAM (MiB)
      THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
      INTERVAL=60s

      echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."

      while true; do
      meminfo=$(cat /proc/meminfo)
      free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
      available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
      inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
      reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
      usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
      if test -z "$available"; then
      message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
      notify-send "Error while monitoring low memory" "$message"
      echo "$message" 1>&2
      exit 1
      fi

      message="Available: $available MiB
      Free: $free MiB
      Maybe usable: $usable MiB"

      if [ "$available" -lt "$THRESHOLD" ]
      then
      notify-send -u critical "Low memory warning" "$message"
      echo "Low memory warning:"
      echo "$message"
      fi

      #echo "DEBUG: $message"
      sleep $INTERVAL
      done





      share|improve this answer


























      • Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

        – Dan Dascalescu
        Feb 13 at 8:36













      • Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

        – Mikko Rantalainen
        Feb 13 at 14:11
















      1














      Another script that I wrote for this purpose:



      #!/bin/bash
      # Copyright 2019, Mikko Rantalainen
      # License: MIT X License

      # Minimum available memory until warning, default to 10% of total RAM (MiB)
      THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
      INTERVAL=60s

      echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."

      while true; do
      meminfo=$(cat /proc/meminfo)
      free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
      available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
      inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
      reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
      usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
      if test -z "$available"; then
      message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
      notify-send "Error while monitoring low memory" "$message"
      echo "$message" 1>&2
      exit 1
      fi

      message="Available: $available MiB
      Free: $free MiB
      Maybe usable: $usable MiB"

      if [ "$available" -lt "$THRESHOLD" ]
      then
      notify-send -u critical "Low memory warning" "$message"
      echo "Low memory warning:"
      echo "$message"
      fi

      #echo "DEBUG: $message"
      sleep $INTERVAL
      done





      share|improve this answer


























      • Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

        – Dan Dascalescu
        Feb 13 at 8:36













      • Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

        – Mikko Rantalainen
        Feb 13 at 14:11














      1












      1








      1







      Another script that I wrote for this purpose:



      #!/bin/bash
      # Copyright 2019, Mikko Rantalainen
      # License: MIT X License

      # Minimum available memory until warning, default to 10% of total RAM (MiB)
      THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
      INTERVAL=60s

      echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."

      while true; do
      meminfo=$(cat /proc/meminfo)
      free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
      available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
      inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
      reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
      usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
      if test -z "$available"; then
      message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
      notify-send "Error while monitoring low memory" "$message"
      echo "$message" 1>&2
      exit 1
      fi

      message="Available: $available MiB
      Free: $free MiB
      Maybe usable: $usable MiB"

      if [ "$available" -lt "$THRESHOLD" ]
      then
      notify-send -u critical "Low memory warning" "$message"
      echo "Low memory warning:"
      echo "$message"
      fi

      #echo "DEBUG: $message"
      sleep $INTERVAL
      done





      share|improve this answer















      Another script that I wrote for this purpose:



      #!/bin/bash
      # Copyright 2019, Mikko Rantalainen
      # License: MIT X License

      # Minimum available memory until warning, default to 10% of total RAM (MiB)
      THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
      INTERVAL=60s

      echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."

      while true; do
      meminfo=$(cat /proc/meminfo)
      free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
      available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
      inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
      reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
      usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
      if test -z "$available"; then
      message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
      notify-send "Error while monitoring low memory" "$message"
      echo "$message" 1>&2
      exit 1
      fi

      message="Available: $available MiB
      Free: $free MiB
      Maybe usable: $usable MiB"

      if [ "$available" -lt "$THRESHOLD" ]
      then
      notify-send -u critical "Low memory warning" "$message"
      echo "Low memory warning:"
      echo "$message"
      fi

      #echo "DEBUG: $message"
      sleep $INTERVAL
      done






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Feb 13 at 8:59









      David Foerster

      28.4k1366111




      28.4k1366111










      answered Jan 29 at 7:35









      Mikko RantalainenMikko Rantalainen

      612615




      612615













      • Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

        – Dan Dascalescu
        Feb 13 at 8:36













      • Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

        – Mikko Rantalainen
        Feb 13 at 14:11



















      • Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

        – Dan Dascalescu
        Feb 13 at 8:36













      • Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

        – Mikko Rantalainen
        Feb 13 at 14:11

















      Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

      – Dan Dascalescu
      Feb 13 at 8:36







      Why o why does notify-send ignore the timeout parameter :-/ And why is there no documentation about what the categories and stock icons are? Also, newlines are ignored and the message gets truncated. -u critical solves that.

      – Dan Dascalescu
      Feb 13 at 8:36















      Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

      – Mikko Rantalainen
      Feb 13 at 14:11





      Technically notify-send does not ignore the timeout. It's the process that takes the notication as input and displays it above the desktop that decides to ignore the timeout. See also: unix.stackexchange.com/q/251243/20336

      – Mikko Rantalainen
      Feb 13 at 14:11











      0














      Updated version of the script which works with free from procps-ng 3.3.10



      #!/bin/bash

      #Minimum available memory limit, MB
      THRESHOLD=400

      #Check time interval, sec
      INTERVAL=30

      while :
      do
      free_out=$(free -w -m)
      available=$(awk '/^Mem:/{print $8}' <<<$free_out)

      if (( $available < $THRESHOLD ))
      then
      notify-send -u critical "Memory is running out!" "Available memory is $available MiB"
      echo "Warning - available memory is $available MiB"
      fi

      cat <<<$free_out
      sleep $INTERVAL
      done





      share|improve this answer




























        0














        Updated version of the script which works with free from procps-ng 3.3.10



        #!/bin/bash

        #Minimum available memory limit, MB
        THRESHOLD=400

        #Check time interval, sec
        INTERVAL=30

        while :
        do
        free_out=$(free -w -m)
        available=$(awk '/^Mem:/{print $8}' <<<$free_out)

        if (( $available < $THRESHOLD ))
        then
        notify-send -u critical "Memory is running out!" "Available memory is $available MiB"
        echo "Warning - available memory is $available MiB"
        fi

        cat <<<$free_out
        sleep $INTERVAL
        done





        share|improve this answer


























          0












          0








          0







          Updated version of the script which works with free from procps-ng 3.3.10



          #!/bin/bash

          #Minimum available memory limit, MB
          THRESHOLD=400

          #Check time interval, sec
          INTERVAL=30

          while :
          do
          free_out=$(free -w -m)
          available=$(awk '/^Mem:/{print $8}' <<<$free_out)

          if (( $available < $THRESHOLD ))
          then
          notify-send -u critical "Memory is running out!" "Available memory is $available MiB"
          echo "Warning - available memory is $available MiB"
          fi

          cat <<<$free_out
          sleep $INTERVAL
          done





          share|improve this answer













          Updated version of the script which works with free from procps-ng 3.3.10



          #!/bin/bash

          #Minimum available memory limit, MB
          THRESHOLD=400

          #Check time interval, sec
          INTERVAL=30

          while :
          do
          free_out=$(free -w -m)
          available=$(awk '/^Mem:/{print $8}' <<<$free_out)

          if (( $available < $THRESHOLD ))
          then
          notify-send -u critical "Memory is running out!" "Available memory is $available MiB"
          echo "Warning - available memory is $available MiB"
          fi

          cat <<<$free_out
          sleep $INTERVAL
          done






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Feb 28 at 10:25









          Jirka HladkyJirka Hladky

          1




          1























              0














              Updated above script to also add details on top 3 memory-hungry processes.
              See at https://github.com/romanmelko/ubuntu-low-mem-popup



              Here is the script itself:



              #!/usr/bin/env bash

              set -o errexit
              set -o pipefail
              set -o nounset

              # If the language is not English, free will output localized text and parsing fails
              LANG=en_US.UTF-8

              THRESHOLD=500
              INTERVAL=300
              POPUP_DELAY=999999

              # sleep some time so the shell starts properly
              sleep 60

              while :
              do
              available=$(free -mw | awk '/^Mem:/{print $8}')
              if [ $available -lt $THRESHOLD ]; then
              title="Low memory! $available MB available"
              message=$(top -bo %MEM -n 1 | grep -A 3 PID | awk '{print $(NF - 6) " t" $(NF)}')
              # KDE Plasma notifier
              kdialog --title "$title" --passivepopup "$message" $POPUP_DELAY
              # use the following command if you are not using KDE Plasma, comment the line above and uncomment the line below
              # please note that timeout for notify-send is represented in milliseconds
              # notify-send -u critical "$title" "$message" -t $POPUP_DELAY
              fi
              sleep $INTERVAL
              done





              share|improve this answer










              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





















              • Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

                – Marc Vanhoomissen
                Mar 6 at 14:07
















              0














              Updated above script to also add details on top 3 memory-hungry processes.
              See at https://github.com/romanmelko/ubuntu-low-mem-popup



              Here is the script itself:



              #!/usr/bin/env bash

              set -o errexit
              set -o pipefail
              set -o nounset

              # If the language is not English, free will output localized text and parsing fails
              LANG=en_US.UTF-8

              THRESHOLD=500
              INTERVAL=300
              POPUP_DELAY=999999

              # sleep some time so the shell starts properly
              sleep 60

              while :
              do
              available=$(free -mw | awk '/^Mem:/{print $8}')
              if [ $available -lt $THRESHOLD ]; then
              title="Low memory! $available MB available"
              message=$(top -bo %MEM -n 1 | grep -A 3 PID | awk '{print $(NF - 6) " t" $(NF)}')
              # KDE Plasma notifier
              kdialog --title "$title" --passivepopup "$message" $POPUP_DELAY
              # use the following command if you are not using KDE Plasma, comment the line above and uncomment the line below
              # please note that timeout for notify-send is represented in milliseconds
              # notify-send -u critical "$title" "$message" -t $POPUP_DELAY
              fi
              sleep $INTERVAL
              done





              share|improve this answer










              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





















              • Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

                – Marc Vanhoomissen
                Mar 6 at 14:07














              0












              0








              0







              Updated above script to also add details on top 3 memory-hungry processes.
              See at https://github.com/romanmelko/ubuntu-low-mem-popup



              Here is the script itself:



              #!/usr/bin/env bash

              set -o errexit
              set -o pipefail
              set -o nounset

              # If the language is not English, free will output localized text and parsing fails
              LANG=en_US.UTF-8

              THRESHOLD=500
              INTERVAL=300
              POPUP_DELAY=999999

              # sleep some time so the shell starts properly
              sleep 60

              while :
              do
              available=$(free -mw | awk '/^Mem:/{print $8}')
              if [ $available -lt $THRESHOLD ]; then
              title="Low memory! $available MB available"
              message=$(top -bo %MEM -n 1 | grep -A 3 PID | awk '{print $(NF - 6) " t" $(NF)}')
              # KDE Plasma notifier
              kdialog --title "$title" --passivepopup "$message" $POPUP_DELAY
              # use the following command if you are not using KDE Plasma, comment the line above and uncomment the line below
              # please note that timeout for notify-send is represented in milliseconds
              # notify-send -u critical "$title" "$message" -t $POPUP_DELAY
              fi
              sleep $INTERVAL
              done





              share|improve this answer










              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.










              Updated above script to also add details on top 3 memory-hungry processes.
              See at https://github.com/romanmelko/ubuntu-low-mem-popup



              Here is the script itself:



              #!/usr/bin/env bash

              set -o errexit
              set -o pipefail
              set -o nounset

              # If the language is not English, free will output localized text and parsing fails
              LANG=en_US.UTF-8

              THRESHOLD=500
              INTERVAL=300
              POPUP_DELAY=999999

              # sleep some time so the shell starts properly
              sleep 60

              while :
              do
              available=$(free -mw | awk '/^Mem:/{print $8}')
              if [ $available -lt $THRESHOLD ]; then
              title="Low memory! $available MB available"
              message=$(top -bo %MEM -n 1 | grep -A 3 PID | awk '{print $(NF - 6) " t" $(NF)}')
              # KDE Plasma notifier
              kdialog --title "$title" --passivepopup "$message" $POPUP_DELAY
              # use the following command if you are not using KDE Plasma, comment the line above and uncomment the line below
              # please note that timeout for notify-send is represented in milliseconds
              # notify-send -u critical "$title" "$message" -t $POPUP_DELAY
              fi
              sleep $INTERVAL
              done






              share|improve this answer










              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.









              share|improve this answer



              share|improve this answer








              edited 2 days ago





















              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.









              answered Mar 6 at 13:27









              Roman MelkoRoman Melko

              11




              11




              New contributor




              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.





              New contributor





              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              Roman Melko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.













              • Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

                – Marc Vanhoomissen
                Mar 6 at 14:07



















              • Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

                – Marc Vanhoomissen
                Mar 6 at 14:07

















              Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

              – Marc Vanhoomissen
              Mar 6 at 14:07





              Thank you for for contribution. The better practice here is to summarize (in this case copy) the content of the link you refer to. This way, your answer remains valid even if the link disappears.

              – Marc Vanhoomissen
              Mar 6 at 14:07











              0














              Variant using percentages and displays notification when called by cron:



              #!/usr/bin/env bash

              eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ | tr '' 'n')";

              FREE_THRESHOLD=5

              free_output=$(free)

              mem_total=$(awk '/^Mem:/{print $2}' <<< $free_output)
              mem_free=$(awk '/^Mem:/{print $4}' <<< $free_output)
              mem_free_m=$(bc <<< "scale=1; $mem_free/1024")
              percent_free=$(bc <<< "scale=1; $mem_free*100 /$mem_total")
              should_warn=$(bc <<< "$percent_free < $FREE_THRESHOLD")

              if (( $should_warn )); then
              notify-send "Memory warning - only $percent_free% ($mem_free_m MB) free"
              else
              echo "Memory OK - $percent_free% ($mem_free_m MB) free"
              fi





              share|improve this answer








              New contributor




              lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.

























                0














                Variant using percentages and displays notification when called by cron:



                #!/usr/bin/env bash

                eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ | tr '' 'n')";

                FREE_THRESHOLD=5

                free_output=$(free)

                mem_total=$(awk '/^Mem:/{print $2}' <<< $free_output)
                mem_free=$(awk '/^Mem:/{print $4}' <<< $free_output)
                mem_free_m=$(bc <<< "scale=1; $mem_free/1024")
                percent_free=$(bc <<< "scale=1; $mem_free*100 /$mem_total")
                should_warn=$(bc <<< "$percent_free < $FREE_THRESHOLD")

                if (( $should_warn )); then
                notify-send "Memory warning - only $percent_free% ($mem_free_m MB) free"
                else
                echo "Memory OK - $percent_free% ($mem_free_m MB) free"
                fi





                share|improve this answer








                New contributor




                lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.























                  0












                  0








                  0







                  Variant using percentages and displays notification when called by cron:



                  #!/usr/bin/env bash

                  eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ | tr '' 'n')";

                  FREE_THRESHOLD=5

                  free_output=$(free)

                  mem_total=$(awk '/^Mem:/{print $2}' <<< $free_output)
                  mem_free=$(awk '/^Mem:/{print $4}' <<< $free_output)
                  mem_free_m=$(bc <<< "scale=1; $mem_free/1024")
                  percent_free=$(bc <<< "scale=1; $mem_free*100 /$mem_total")
                  should_warn=$(bc <<< "$percent_free < $FREE_THRESHOLD")

                  if (( $should_warn )); then
                  notify-send "Memory warning - only $percent_free% ($mem_free_m MB) free"
                  else
                  echo "Memory OK - $percent_free% ($mem_free_m MB) free"
                  fi





                  share|improve this answer








                  New contributor




                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.










                  Variant using percentages and displays notification when called by cron:



                  #!/usr/bin/env bash

                  eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ | tr '' 'n')";

                  FREE_THRESHOLD=5

                  free_output=$(free)

                  mem_total=$(awk '/^Mem:/{print $2}' <<< $free_output)
                  mem_free=$(awk '/^Mem:/{print $4}' <<< $free_output)
                  mem_free_m=$(bc <<< "scale=1; $mem_free/1024")
                  percent_free=$(bc <<< "scale=1; $mem_free*100 /$mem_total")
                  should_warn=$(bc <<< "$percent_free < $FREE_THRESHOLD")

                  if (( $should_warn )); then
                  notify-send "Memory warning - only $percent_free% ($mem_free_m MB) free"
                  else
                  echo "Memory OK - $percent_free% ($mem_free_m MB) free"
                  fi






                  share|improve this answer








                  New contributor




                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  share|improve this answer



                  share|improve this answer






                  New contributor




                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered 2 days ago









                  lambfrierlambfrier

                  1




                  1




                  New contributor




                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  lambfrier is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Ask Ubuntu!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f234292%2fwarning-when-available-ram-approaches-zero%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Human spaceflight

                      Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

                      張江高科駅