Skip to content

Instantly share code, notes, and snippets.

@pialechini
Created April 21, 2024 18:41
Show Gist options
  • Select an option

  • Save pialechini/ce220d27ad2a220b8e7233dd9ea4132a to your computer and use it in GitHub Desktop.

Select an option

Save pialechini/ce220d27ad2a220b8e7233dd9ea4132a to your computer and use it in GitHub Desktop.

Revisions

  1. pialechini created this gist Apr 21, 2024.
    52 changes: 52 additions & 0 deletions battery-alarm-notifier.bash
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #!/bin/bash

    # Description
    # ===========
    # This script monitors the battery status on Linux systems
    # and notifies the user if the battery is either charging
    # and above 80% or discharging and below 20%. This script
    # can be scheduled to run periodically using cron or
    # other scheduling utilities. if you decide to use cron,
    # run "crontab -e" and add the following line:
    # * * * * * bash /absolute/path/to/this-file

    # Requirements
    # ============
    # KDE Desktop and "libnotify-bin" installed with apt.


    # Customizable
    UPPER_BOUND=80
    LOWER_BOUND=20

    get_battery_percentage() {
    local percentage=$(upower -i $(upower -e | grep 'BAT') | grep percentage | awk '{print $2}')
    echo "${percentage%\%}" # Remove the '%' sign
    }

    is_battery_charging() {
    local charging_status=$(upower -i $(upower -e | grep 'BAT') | grep state | awk '{print $2}')
    if [[ "$charging_status" == "charging" ]]; then
    return 0
    else
    return 1
    fi
    }

    is_battery_discharging() {
    local charging_status=$(upower -i $(upower -e | grep 'BAT') | grep state | awk '{print $2}')
    if [[ "$charging_status" == "discharging" ]]; then
    return 0
    else
    return 1
    fi
    }


    battery_percentage=$(get_battery_percentage)

    if is_battery_charging && (( battery_percentage > $UPPER_BOUND )); then
    XDG_RUNTIME_DIR=/run/user/$(id -u) notify-send -u normal "Unplug charger! Current battery percentage: $battery_percentage%"
    elif is_battery_discharging && (( battery_percentage < $LOWER_BOUND )); then
    XDG_RUNTIME_DIR=/run/user/$(id -u) notify-send -u normal "Plug charger! Current battery percentage: $battery_percentage%"
    fi