DEV Community

Cover image for A 34-liner shell script to save your productivity
Dario Mannu
Dario Mannu

Posted on

A 34-liner shell script to save your productivity

Your #1 productivity killer may lay inside the very tool you use most often: Chrome.

It's been like that for years. Memory leaks adding up, certainly a lot in the browser itself in the past, but a few still in poorly written webapps such as LinkedIn, the Google Cloud console, Youtube, Google Ad Manager, just to name some of my top offenders of the moment.

If you're on Linux it can get crazy: it eats up the last bits of your RAM, then it's over: all CPUs start burning coal, your laptop takes off, your mouse can barely move, your work is over.

If you thought The Great Suspender or Auto Tab Discard were going to save you... I wish...


For years I've been battling this with no luck... until now, after yet another round of discussions with our best friend (ChatGPT), when we finally appear to have reached a turning point.

It's a tiny script that periodically checks the top offenders by memory consumption (among chrome processes) and when there's less than a certain amount of free memory, it tries to softly terminate the first one. If it doesn't respond, it goes with a KILL signal, just in case.

And finally we can keep working normally without having to restart the whole browser or the system every 2 days.

#!/bin/bash

THRESHOLD_MB=1024
CHECK_INTERVAL=20

while true; do
  free_mem=$(free -m | awk '/^Mem:/{print $7}')
  # echo "FREE MEM: ${free_mem}"

  if [ "$free_mem" -lt "$THRESHOLD_MB" ]; then
    # Get the PID of the Chrome tab using the most RAM
    top_pid=$(ps -eo pid,%mem,cmd --sort=-%mem | grep '[c]hrome --type=renderer' | head -n 1 | awk '{print $1}')

    if [ -n "$top_pid" ]; then
      echo "Warning: Low memory ($free_mem MB free). Attempting to terminate Chrome tab with PID $top_pid..."

    # Try graceful termination first
    kill -15 "$top_pid"
    sleep 10  # Give it some time to close

    # Check if process is still running
    if ps -p "$top_pid" > /dev/null; then
      echo "Tab did not close, forcing termination with SIGKILL."
      kill -9 "$top_pid"
    else
      echo "Tab closed successfully."
    fi
  else
    echo "No Chrome tab found to terminate."
    fi
  fi

  sleep "$CHECK_INTERVAL"
done

Enter fullscreen mode Exit fullscreen mode

You just run this script and it works. No need to start chrome with weird cgroups or other nonsense, so should be pretty easy to use.

Hope that helps...

Top comments (0)