Tmux – How to Start with Attach if a Session Exists

tmux

If I use

tmux attach

I can attach to a running session but if there is no session running, I only get the error

no sessions

How can I automatically start a new session if there is none running? something like

tmux attach-or-create-new-session

Best Answer

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.

Related Question