Script turning screen off when brightness dips below 5%

Hello everyone,

I just signed up to post this so please forgive me if I didn’t post it in the right section but I just created a little ZSH script that dynamically checks for the name of display with dbus and listens for KDE signals indicating a screen brightness change and, when the brightness dips below 5%, turns the screen off when the brightness is set to 0%.

Please note that, being a complete beginner in shell scripting, I used Google Gemini to get things to work the way I wanted them to so, if anyone can provide recommendations/tweaks to make the script better (and teach me something), I would be very grateful!

Also, this script has to be executed on startup by KDE (which I did with the Autostart section of KDE’s system settings) so the user will have to chmod u+x my_script_file.sh in order for it to work.

No custom shortcuts are needed in KDE as the script listens for events triggered by the stock Increase Screen Brightness key.

Here is the script:

#!/bin/zsh

# 1. Dynamically fetch the active display's DBus name at runtime
# This extracts the string between the quotes from KDE's display list array
DISPLAY_NAME=$(dbus-send --session --print-reply --dest=org.kde.ScreenBrightness /org/kde/ScreenBrightness org.freedesktop.DBus.Properties.Get string:"o
rg.kde.ScreenBrightness" string:"DisplaysDBusNames" | awk -F'"' '/string/ {print $2; exit}')

# Fallback safety guard: If DBus fails to return a name, default to display0
[[ -z "$DISPLAY_NAME" ]] && DISPLAY_NAME="display0"

# 2. Passive event listener using the dynamic display name
# This waits for KDE to signal a brightness property change on the detected display
dbus-monitor --session "type='signal',path='/org/kde/ScreenBrightness/$DISPLAY_NAME',interface='org.freedesktop.DBus.Properties',member='PropertiesChang
ed'" | while read -r line; do

# Filter for the main signal header line to prevent duplicate checks
if [[ "$line" == *"member=PropertiesChanged"* ]]; then

# 3. Capture the current brightness level (%) using the dynamic display path
BRIGHTNESS=$(dbus-send --session --print-reply --dest=org.kde.ScreenBrightness /org/kde/ScreenBrightness/$DISPLAY_NAME org.freedesktop.DBus.Prop
erties.Get string:"org.kde.ScreenBrightness.Display" string:"Brightness" | awk '/variant/ {print $3/100}')

# 4. If brightness drops below 5%, trigger the screen off shortcut
if (( BRIGHTNESS < 5 )); then
dbus-send --session --print-reply --dest=org.kde.kglobalaccel /component/org_kde_powerdevil org.kde.kglobalaccel.Component.invokeShortcut st
ring:"Turn Off Screen"
fi
fi
done

I hope this helps!