Bash – Start shell with tmux and attach only to a session if it is unattached

bashshelltmuxzsh

I am currently starting tmux when opening my shell, which the following config for my shell

[[ $TMUX == "" ]] && tmux new-session

Is there any way to start my shell and attach tmux to the (first) unattached session, if one exists? If a shell is already attached to that session I don't want to attach to that.

Best Answer

I think you can achieve what you're looking for by using an appropriate format with tmux list-session and parsing the output:

if [ -z "$TMUX" ]; then
    attach_session=$(tmux 2> /dev/null ls -F \
        '#{session_attached} #{?#{==:#{session_last_attached},},1,#{session_last_attached}} #{session_id}' |
        awk '/^0/ { if ($2 > t) { t = $2; s = $3 } }; END { if (s) printf "%s", s }')

    if [ -n "$attach_session" ]; then
        tmux attach -t "$attach_session"
    else
        tmux
    fi
fi

The format here for tmux ls gives, for each session, the number of clients attached, time when last attached (or 1 if never attached before, such as after tmux new -d), and session ID. The AWK script uses this information to find the most recently attached session with no currently attached clients and outputs its ID. We then either attach to that session or create a new one if no such session is found, like when the server isn't started or every existing session is attached.

Related Question