Is there a way to run a bash script on locking the current KDE session?


On KDE and some other Desktop Environments, you can listen on dbus for the interface org.freedesktop.ScreenSaver.

A script to do this would look like this:

dbus-monitor --session "type='signal',interface='org.freedesktop.ScreenSaver'" |
  while read x; do
    case "$x" in 
      # You can call your desired script in the following line instead of the echo:
      *"boolean true"*) echo SCREEN_LOCKED;;
      *"boolean false"*) echo SCREEN_UNLOCKED;;  

Please also see this question for more information.


It might depend on which version of KDE you're running, but if you've got a Notifications Entry in System Settings, then you can use the Screensaver controls to run scripts on both screen lock and unlock.

KDE Notifications System Settings Module


One workaround I can think of is (if you normally use a keyboard shortcut to lock) to rebind the keyboard shortcut from lock to instead execute your script, then locking the session, which can be achieved using this command in your script:

qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock

However, I'm not on kde, so can't test it.

If you don't use a keyboard shortcut, I think it will be harder to do this. One possible method is forking the locking program to look for a script and execute it.

  • Although this looks like a hack, I prefer this answer to the dbus monitor solution, since it does not require the script to be running during the complete session. Especially if you are doing something security sensitive (e.g. close ssh keys), you will not notice a terminated dbus monitor script (and in the example you would leave keys in memory). – Till Schäfer Nov 6 '19 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.