How to create new tmux session if none exists

Solution 1:

I figured it out (and had it pointed out to me).

tmux attach || tmux new

Solution 2:

Alternately, you can add

new-session

to your .tmux.conf - that will create a default session on server start.

Then tmux attach will either attach to the current session (running server, that is), or create a new session (start the server, read the config file, issue the new-session command) and attach to that.

Solution 3:

As pointed out in comments from Petr Viktorin, jkoelker and pjincz, you can use the following command to attach to mySession if it exists, and to create it if it doesn't:

 tmux new -A -s mySession

From man tmux:

new-session[-AdDEP] [-cstart-directory] [-Fformat] [-nwindow-name] [-ssession-name] [-tgroup-name] [-xwidth] [-yheight] [shell-command]

(alias: new)

Create a new session with name session-name.

[...]

The -A flag makes new-session behave like attach-session if session-name already exists; in this case, -D behaves like -d to attach-session.

new-session has supported -A since tmux-1.8.