10

KDE Konsole does not have a feature to save the current session (opened tabs, current directory etc.)

How can we save/restore the current session?

intika
  • 13,920
  • 7
  • 41
  • 79
  • 1
    Actually, as of KDE 5.18.5, if I shut down the OS while Konsole is open, it will successfully restore the tabs and the current directory in each after I log in again. The scrollback buffer is lost though (as expected). – Dan Dascalescu Feb 14 '21 at 12:50

1 Answers1

8

Create ~/.konsole/watcher.sh and make it executable (chmod 755 watcher.sh) then add it to the startup applications.

We can start konsole in a restored mode with konsole --tabs-from-file ~/.konsole/current-tabs or with ~/.konsole/watcher.sh restore.

#!/bin/bash

# ~/.konsole/watcher.sh

# Watches the konsole qdbus messages and saves session state changes so they can be restored easily
# https://docs.kde.org/trunk5/en/applications/konsole/command-line-options.html

# Configuration
COMMAND=''
WATCH_INTERVAL_SECONDS=15
SAVEFILE_TERMINAL="${HOME}/.konsole/current-tabs"

# Restore if asked to
if [ "$1" = "restore" ] ; then
    echo "Restoring..."
    konsole --tabs-from-file ${SAVEFILE_TERMINAL} -e 'bash -c exit'&
fi

# Function to get the current sessions and write them to a file
function getSessions {
    pid=$(pgrep konsole -u $USER)
    local SESSIONS=$(qdbus org.kde.konsole-$pid | grep /Sessions/)
    if [[ ${SESSIONS} ]] ; then
       echo "# Most recent session list " $(date) > ${SAVEFILE_TERMINAL}
       for i in ${SESSIONS}; do
       local FORMAT=$(qdbus org.kde.konsole-$pid $i tabTitleFormat 0)
       local PROCESSID=$(qdbus org.kde.konsole-$pid $i processId)
       local CWD=$(pwdx ${PROCESSID} | sed -e "s/^[0-9]*: //")
       if [[ $(pgrep --parent ${PROCESSID}) ]] ; then
           CHILDPID=$(pgrep --parent ${PROCESSID})
           COMMAND=$(ps -p ${CHILDPID} -o args=)
       fi 
       echo "workdir: ${CWD};; title: ${FORMAT};; command:${COMMAND}" >> ${SAVEFILE_TERMINAL}
       COMMAND=''
       done
    fi
}

#Update the Konsole sessions every WATCH_INTERVAL_SECONDS seconds
while true; do sleep ${WATCH_INTERVAL_SECONDS}; getSessions; done &
intika
  • 13,920
  • 7
  • 41
  • 79
  • Thank you! This is really useful! – Subin Jul 03 '21 at 08:27
  • 1
    A few notes for others using this code: 1. Don't include the word `konsole` in your script name or it would break. 2. This won't support more than one konsole apps running. 3. It may not work if you try to run it from a shell terminal, kde needs to run it directly – Ramast Dec 29 '21 at 11:25