Blog/Home is where your screen session is
In this article I want to take a small note on how I configured a systemd unit to automatically start a detatched screen session.
I want to always have a screen session started for my users (mainly root and my unprivileged users).
Enable the systemd user instance.
Run (as root): loginctl enable-linger myuser.
This will enable the startup of an unprivileged systemd session. It will automatically start user units.
Create the user unit
Make sure the unit directory exists: mkdir -p ~/.config/systemd/user
Create the file name ~/.config/systemd/user/screen-default.service with the following contents:
[Unit]
Description=Default Screen session
Wants=default.target
After=default.target
[Service]
Type=simple
ExecStart=screen -DmS default
Restart=always
RestartSec=3
StartLimitBurst=1
[Install]
WantedBy=default.target
Enable and start
As simple as running systemctl --user enable --now screen-default.service
Screen parameters details
This is interesting:
- -D start screen in detached mode, but does not perform e fork before starting
- This means that the main process will not exit (and systemd will be able to track it)
- screen wil exit when the session terminates
- -d would perform a fork
- -m ignores the $TTY environment variable, so it will not complain
- -s default sets the session name to default
Other interesting parameters
The Restart/RestartSec/StartLimitBurts make it possible for systemd to always restart the unit.
Meaning that there will always be a screen session ready.
A copy-paste ready version
So I've done it a few times and I guess it's better to have a single copy-paste ready version
# sudo loginctl enable-linger `whoami`
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/screen-default.service <<EOF
[Unit]
Description=Default Screen session
Wants=default.target
After=default.target
[Service]
Type=simple
ExecStart=screen -DmS default
Restart=always
RestartSec=3
StartLimitBurst=1
[Install]
WantedBy=default.target
EOF
systemctl --user enable --now screen-default.service
My .screenrc
To make this post complete, here is my .screenrc:
defmousetrack off
mousetrack off
## details about RUNNING_IN_SCREEN later
setenv RUNNING_IN_SCREEN t
# might be needed on mac os
#shell "/opt/homebrew/bin/bash"
## get out of my way...
startup_message off
defflow off
layout new default
layout select default
layout autosave on
hardstatus on
hardstatus alwayslastline
# hardstatus string "$USER@%H > %S > %-w | %t | %+w "
hardstatus string "%{.kr}%3`>%{..g}%2`>%{.kw}%-w >%{.kG}%t%{.kw}< %+w %=%{..g}|%l|%{..y} %1`"
backtick 0 3600 3600 whoami
backtick 1 10 10 date "+%d/%m/%y %H:%M"
backtick 2 10 3600 sh -c 'screen -ls | grep --color=no -o "$PPID[^[:space:]]*" | cut -d. -f 2'
backtick 3 3600 3600 hostname
## remove lock screen feature
bind x
