How to start tmux with attach if a session exists
If naming your session is okay, then it's easy to do with the new-session
command:
tmux new-session -A -s main
where main
is the session name that will be attached to or created if needed.
From man tmux
:
The
-A
flag makesnew-session
behave likeattach-session
if session-name already exists; in this case,-D
behaves like-d
toattach-session
.
This can be shortened to rely on the default session name (which is 0
):
tmux new -As0
Please also note that the -A
option was introduced in tmux version 1.8
on 26 March 2013. For earlier versions, use:
tmux attach || tmux
The answer is much simpler. Just put this in your ~/.tmux.conf
file:
# if run as "tmux attach", create a session if one does not already exist
new-session -n $HOST
If you run tmux attach
and there is a session, then it will attach to that session (whether it's already attached or not). If there is not a session already then it will create one for you.
This will start a new session if attach gives an error:
tmux attach || tmux new
So an alias will do the job:
tm="tmux attach || tmux new"