Auto-Reconnect Terminal Sessions with Systemd + Tmux

Configurare noua (How To)

Situatie

You want long-lived terminal sessions that survive SSH disconnects, reboots, and accidental closures — but tmux or screen feel too manual for novice users or scripts. You want this to just happen when you log in.

Solutie

Solution Overview:

Use a systemd user service to automatically spawn (or reattach) to a named tmux session every time you log in.

Steps:

  1. Install tmux:

sudo apt install tmux
  1. Enable systemd lingering for your user so services persist:

sudo loginctl enable-linger $USER
  1. Create the service file:

mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/autotmux.service

Paste this:

[Unit]
Description=Auto-launch tmux session at login
After=network.target
[Service]
ExecStart=/usr/bin/tmux new-session -A -s main
WorkingDirectory=%h
Restart=always

[Install]
WantedBy=default.target

  1. Enable and start the service:

systemctl --user daemon-reexec
systemctl --user enable autotmux
systemctl --user start autotmux
  1. Optional: Add this to .bashrc or .zshrc to auto-attach:

if [ -z "$TMUX" ]; then
tmux attach-session -t main || tmux new-session -s main
fi

Benefits:

  • Session always persists, even if SSH drops.

  • Auto-restarts after reboot.

  • No need to teach someone how to use tmux — it “just works”.

Tip solutie

Permanent

Voteaza

(1 din 2 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?