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?
After consulting the wizards of IRC I am confident there is no single tmux command that has this behavior. Luckily, it is fairly easy to emulate using the shell:
(tmux ls | grep -vq attached && tmux at) || 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`
I tend to only have two tmux sessions at a time, so I do something like this in each terminal window.
terminal window 0:
tmux attach -t 0 || tmux new
terminal window 1:
tmux attach -t 1 || tmux new
This has worked the best for me:
if [ -z "$TMUX" ]; then (tmux ls | grep -vq attached && tmux at -t `tmux ls | grep -vm1 attached | cut -d: -f1`) || tmux new fi
The -t is needed to attach to the proper session.
tmux attach || tmux new
or instead just create the file
~/.tmux.conf if it doesn't exist, and add
to it such that it creates a new session when there is none when you run
It might also be handy to make
tmux an alias to