The command notify-send
needs the environment variable DBUS_SESSION_BUS_ADDRESS
set and must be called with the owner of this session bus as user.
In the following script the function notify_users
searches for all dbus-daemons that control a session bus. The command line of such a daemon looks like this:
dbus-daemon --fork --session --address=unix:abstract=/tmp/dbus-ceVHx19Kiy
For this processes the owner and the dbus address is determined. Then we are able to use notify-send
. This script should inform all user logged in with a GDM session. But I never tested that.
Note: If you call this as non-root, you might get queried for a password due to the use of sudo
.
#!/bin/bash
# Inform all logged on users
# Usage: notify_users TITLE MESSAGE [urgency [icon]]
notify_users()
{
typeset title="$1"
typeset message="$2"
typeset urgency="${3:-critical}"
typeset icon="${4:-}"
case "$urgency" in
"low") : ;;
"normal") : ;;
"critical") : ;;
*)
urgency="normal"
;;
esac
typeset ls user bus_addr
typeset IFS=$'\n'
# for all dbus-daemon processes that create a session bus
for ln in "$(ps -eo user,args | grep "dbus-daemon.*--session.*--address=" | grep -v grep)"; do
# get the user name
user="$(echo "$ln" | cut -d' ' -f 1)"
# get dbus address
bus_addr="$(echo "$ln" | sed 's/^.*--address=//;s/ .*$//')"
# run notify-send with the correct user
DBUS_SESSION_BUS_ADDRESS="$bus_addr" sudo -u $user -E /usr/bin/notify-send -u "$urgency" -i "$icon" "$title" "$message"
done
}
state="$(upower -i $(upower -e | grep BAT))"
# if the state contains the word "discharging"
if [[ "$state" = *discharging* ]]; then
perc=$(echo "$state" | grep "percentage" | awk '{print $2}' | tr -d '%')
icon="$(echo "$state" | grep "icon-name:" | awk '{print $2}' | tr -d "'\"" )"
if [ "$perc" -lt 15 ]; then
notify_users "Battery Low!" "Please plugin charger ... charge is only $perc%" "critical" "$icon"
fi
fi