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: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 aftertmux 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.