Last Updated: February 25, 2016
· faceleg

Auto-attach or start tmux at login

Use as part of a ~/.zshrc (or similar) to have your shell automatically attach itself to the running tmux session for your user, or create one if none exist.

But only if not already inside a session & not logged in via SSH.

This prevents tmux panes from attempting to nest tmux sessions, and prevents a tmus session from being started when SSH-ing into a machine sharing a similar ~/.zshrc file.

if [[ "$TERM" != "screen" ]] && 
        [[ "$SSH_CONNECTION" == "" ]]; then
    # Attempt to discover a detached session and attach 
    # it, else create a new session

    if tmux has-session -t $WHOAMI 2>/dev/null; then
        tmux -2 attach-session -t $WHOAMI
        tmux -2 new-session -s $WHOAMI

    # One might want to do other things in this case, 
    # here I print my motd, but only on servers where 
    # one exists

    # If inside tmux session then print MOTD
    if [ -f $MOTD ]; then

If one desires that a tmux session is started for SSH connections, simply replace:

       [[ "$SSH_CONNECTION" == "" ]]; then


; then

1 Response
Add your response

Thanks for sharing! If you've got new-session in your tmux config you can simplify this quite a bit. This script would only need to prevent nesting tmux sessions.

over 1 year ago ·