Skip to content

Instantly share code, notes, and snippets.

@Yoxem
Last active November 10, 2019 17:24
Show Gist options
  • Save Yoxem/7ac7549b6c2b486880256157661bb9ba to your computer and use it in GitHub Desktop.
Save Yoxem/7ac7549b6c2b486880256157661bb9ba to your computer and use it in GitHub Desktop.
A shell script used to detect the battery power on Linux laptop and give a warning when the battey is low.
#!/bin/sh
# system-autodetect-battery-and-hibernate
# a shell script used to detect the battery power on Linux laptop and give a warning when the battey is low.
# License: MIT License
# Author: Yoxem Chen
# Date: 2019-11-10 (modified: 2019-11-11)
CRITICAL_PERCENTAGE=5 # in percentage
IS_LOWER_THAN_CRITICAL=false;
# get the current status "charging" or "discharging"
STATUS=`upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep state: | sed 's|[[:space:]]\+state:[[:space:]]\+||g'`;
# get the curreng battery usage
BATTERY_PERCENTAGE=`upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep percentage: | sed -e 's/[[:space:]]\+percentage:[[:space:]]\+\([0-9]\+\)%/\1/g'`;
if [ "${STATUS}" = "discharging" ] && [ "$BATTERY_PERCENTAGE" -lt "$CRITICAL_PERCENTAGE" ]; then
IS_LOWER_THAN_CRITICAL=true;
else
IS_LOWER_THAN_CRITICAL=false;
fi
if [ $IS_LOWER_THAN_CRITICAL = true ]; then
DIALOG_TEXT="目前電量 ${BATTERY_PERCENTAGE}% 低於危險值 ${CRITICAL_PERCENTAGE}% ,以下將進行休眠動作。";
zenity --warning --text="${DIALOG_TEXT}"; # show a warning dialo.
gksu pm-hibernate;
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment