Skip to content

Instantly share code, notes, and snippets.

@rahuldhole
Last active May 9, 2024 19:20
Show Gist options
  • Save rahuldhole/2f1678fd96c0891541932c092bd3fc78 to your computer and use it in GitHub Desktop.
Save rahuldhole/2f1678fd96c0891541932c092bd3fc78 to your computer and use it in GitHub Desktop.
Increase laptop battery life: A Simple Bash Script
#!/bin/bash
# Change Settings
cpu_threshold=30 # max percentage
memory_threshold=95 # max percentage
processes="chrome,code" # Processes to monitor and kill (comma-separated)
# Article to read more: https://dev.to/rahuldhole/managing-resource-deadlocks-a-simple-bash-script-for-linux-1n64
# Function to monitor CPU usage
monitor_cpu() {
cpu_usage=$(top -bn2 | grep '%Cpu' | tail -1 | grep -P '(....|...) id,' | awk '{print 100-$8}')
if awk -v cpu_usage="$cpu_usage" -v cpu_threshold="$cpu_threshold" 'BEGIN { exit !(cpu_usage >= cpu_threshold) }'; then
logger -p user.warning "CPU usage is high ($cpu_usage%), killing selected processes."
kill_processes
fi
}
# Function to monitor memory usage
monitor_memory() {
memory_usage=$(free -m | grep 'Mem:' | awk '{ print $3/$2*100 }')
if awk -v memory_usage="$memory_usage" -v memory_threshold="$memory_threshold" 'BEGIN { exit !(memory_usage >= memory_threshold) }'; then
logger -p user.warning "Memory usage is high ($memory_usage%), killing selected processes."
kill_processes
fi
}
# Function to kill selected processes
kill_processes() {
IFS=',' read -ra process_list <<< "$processes"
for process in "${process_list[@]}"; do
pkill -f "$process"
done
}
# Main logic
monitor_cpu
monitor_memory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment