Automatically start screen or tmux session on SSH login (server-side)

Nelson Aloysio
2 min readAug 24, 2023
Figure: The tmux logo, my choice of a multiplexer.

Both screen and tmux are commonly used terminal multiplexers, which allow to much more easily manage your TTYs (teletypewriters). Configuring a multiplexer session to be opened on SSH login on the host side is useful if you are used to remotely accessing it from distinct clients, for example.

Using screen

Just add the code below to your ~/.bashrc file (or ~/.zshrc.local, if you prefer zsh) — or alternatively to yet another file, provided it is sourced on login:

( [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ] || [ "$(ps -o comm= -p "$PPID")" = "sshd" ] ) &&
[ $(\screen -ls | grep -w "$(whoami)" | grep -ciw attached) -eq 0 ] &&
$( $(systemd-run --scope --user echo 2>/dev/null) && echo -n systemd-run --scope --user) \screen -d -R -S "$(whoami)" &&
exit

The condition on the third line is important for servers running systemd, to ensure the session is not interrupted on logout (see why here and there); if not available (e.g. MacOS/Windows/WSL), systemd-run is simply not called.

From now on, each time you log in as the same user, a screen session with the user name will automatically be started — or reattached, if it exists and is not attached yet. Otherwise, the new shell will just remain open as usual.

Using tmux

The reason I prefer tmux is simple: it allows to split your terminal at will. Likewise, just copy and paste the following code to be sourced on login:

( [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ] || [ "$(ps -o comm= -p "$PPID")" = "sshd" ] ) &&
[ $(\tmux ls | grep -w "$(whoami)" | grep -cw attached) -eq 0 ] &&
$( $(systemd-run --scope --user echo 2>/dev/null) && echo -n systemd-run --scope --user) \tmux new -A -s "$(whoami)" &&
exit

Specially for remote connections, nothing beats a good multiplexer:

Figure: iTerm window running tmux.

Lastly, note that the same code can be easily adapted to other multiplexers.

--

--