Here comes my script, that can shutdown KDE 4 saving current session. It can do the work from a regular user (session owner) and root, that makes it suitable for been run from acpid. Maybe it will help somebody. All comments are welcome.

Code:

# /bin/sh
# Written by cz0 2010
# Distributed under the terms of the GNU General Public License v2

I figured out why the posted script was giving errors. The line that begins with "CURRENT_DBUS_SESSION_BUS_ADDRESS=" and ends with ">" seems to have been truncated. It seems like there is (or at least was) a KDE issue where an important environment variable DBUS_SESSION_BUS_ADDRESS is/was not set properly. This part of the script appears to be a workaround for this problem. I changed the script to automatically set this variable correctly, but only if it is not already set. I think this is safer since at least on my system this variable is already set. I did test that this clever technique for figuring out how KDE set this variable for itself actually works fine.

Below is my attempt at a corrected version. It works for me under Suse 12.1.

I am not sure why Kde does not come with a shell script like this one to allow logging out of Kde without resorting to the menu.

Code:

# /bin/sh
# Written by cz0 2010
# Distributed under the terms of the GNU General Public License v2

# If the DBUS_SESSION_BUS_ADDRESS environment variable is not already set correctly
# then set it by finding the environment file for the startkde process in proc and
# parsing it to get get the correct setting.
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
ENVIRON_FILE=/proc/$(ps h --ppid $KDEPID -o pid | awk '{print $1}')/environ
CURRENT_DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS $ENVIRON_FILE | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//')
export DBUS_SESSION_BUS_ADDRESS=$CURRENT_DBUS_SESSION_BUS_ADDRESS
fi