Skip to content

Instantly share code, notes, and snippets.

@npyoung
Last active July 3, 2026 21:59
Show Gist options
  • Select an option

  • Save npyoung/d63e4bea4333499e75ca03ef15222e75 to your computer and use it in GitHub Desktop.

Select an option

Save npyoung/d63e4bea4333499e75ca03ef15222e75 to your computer and use it in GitHub Desktop.
Auto-attach to most recent tmux session on ssh
# Auto-attach to most recently used tmux session on SSH login, or start fresh
if [[ -n "$SSH_CONNECTION" && -z "$TMUX" ]]; then
last_session=$(tmux list-sessions -F "#{session_last_attached}|#{session_name}" 2>/dev/null | sort -rn | head -1 | cut -d'|' -f2)
if [[ -n "$last_session" ]] && tmux has-session -t "$last_session" 2>/dev/null; then
exec tmux attach-session -t "$last_session" 2>/dev/null || exec bash
else
exec tmux 2>/dev/null || exec bash
fi
fi
# Exit shell when tmux exits
set-option -g exit-empty on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment