How can I attach to the the first tmux session that has no attached clients or, if there are no unattached sessions, create a new session and attach to that?

(The use case is for a command for my terminal emulator to run when opening a new terminal window. I don't want it to create a new session each time I open a window, if there are detached sessions lying around. Nor do I want it to re-attach to the same named session every time, if there's already a window attached to that session. I want it to recycle existing unattached sessions but create new sessions when there are none unattached.)


There may be a simpler way to do this using tmux itself, without resorting to shell scripts. But I got it working by combining a couple of scripts.

The first script prints out the name of the first unattached session. This is ,tmux-first-unattached-session:

#!/usr/bin/env sh
# Print the name of the first tmux session that has no clients attached.
tmux ls -F '#{session_name}|#{?session_attached,attached,not attached}' 2>/dev/null | grep 'not attached$' | tail -n 1 | cut -d '|' -f1

The second script attaches to the first unattached session or a new session:

#!/usr/bin/env sh
# Attach to the first tmux session that has no attached clients.
# If there are no unattached sessions, then create a new session.
tmux attach -t `,tmux-first-unattached-session` 2> /dev/null || tmux

I have something like this which is pretty simple.

  1. Detect if there is an un-attached session, try to attach
  2. Else start a clean session
# Start TMUX first; try to reattach a session
if [[ -z $TMUX ]]; then
  ATTACH_OPT=$(tmux ls | grep -vq attached && echo "attach -d")
  exec eval "tmux $ATTACH_OPT"
  • Is there a reason you're doing exec eval and not just tmux $ATTACH_OPT? – evan Sep 12 '20 at 1:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.