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.