2

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.

1

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.

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.