tmux attach command acts more like a combination of
screen -r and
screen -x -- first it trys to attach to the most recently detached session, and then if none is available it will attach to a currently attached session. I want to emulate the behavior of
screen -R: first try to attach to a detached session, then start a new session if there were no detached sessions. What is the best way to achieve this in tmux?
Despite what it says in tmux manual:
The target-session rules for attach-session are slightly adjusted: if tmux needs to select the most recently used session, it will prefer the most recently used unattached session.
Drew's answer won't work properly in a situation like:
0: 1 windows (created Wed Nov 7 23:51:08 2012) [177x47] 1: 1 windows (created Wed Nov 7 23:51:33 2012) [177x47] (attached)
tmux at will attach to the last session (#1) (even though this session is still attached somewhere else). This ruins the whole idea of running several tmux sessions and attaching only to a detached one (to use mosh + tmux + iterm2 to create a perfect roaming terminal).
Another approach would be to manually select a non-attached session:
tmux ls | grep -vq attached && tmux at `tmux ls | grep -vm1 attached | cut -d: -f1`