Skip to content

Instantly share code, notes, and snippets.

@ercoppa
Created December 3, 2022 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ercoppa/7df17b13f1c85dd7aa6c7bff27d2d679 to your computer and use it in GitHub Desktop.
Save ercoppa/7df17b13f1c85dd7aa6c7bff27d2d679 to your computer and use it in GitHub Desktop.
sleep_critical_power.sh
#!/usr/bin/env bash
# Notifies the user if the battery is low.
# Executes some command (like hibernate) on critical battery.
# This script is supposed to be called from a cron job.
function notify-send() {
# Detect the name of the display in use
local display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"
# Detect the user using such display
local user=$(who | grep '('$display')' | awk '{print $1}' | head -n 1)
# Detect the id of the user
local uid=$(id -u $user)
sudo -u $user DISPLAY=$display DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@"
}
level=$(cat /sys/class/power_supply/BAT0/capacity)
status=$(cat /sys/class/power_supply/BAT0/status)
# Exit if not discharging
if [ "${status}" != "Discharging" ]; then
exit 0
fi
# Percentage at which to show low-battery notification
low_notif_percentage=20
# Percentage at which to show critical-battery notification
critical_notif_percentage=15
# Percentage at which to power-off
critical_action_percentage=10
if [ "${level}" -le ${critical_action_percentage} ]; then
# sudo is required when running from cron
systemctl suspend
exit 0
fi
if [ "${level}" -le ${critical_notif_percentage} ]; then
notify-send -i '/usr/share/icons/gnome/256x256/status/battery-caution.png' "Battery critical: ${level}%"
exit 0
fi
if [ "${level}" -le ${low_notif_percentage} ]; then
notify-send -i '/usr/share/icons/gnome/256x256/status/battery-low.png' "Battery low: $level%"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment