How to create new tmux session if none exists

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

tmux attach || tmux new

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.


Adapting Alex's suggestion to include project based configuration upon startup, I started using the following:

# ~/bin/tmux-myproject shell script
# The Project name is also used as a session name (usually shorter)
PROJECT_NAME="myproject"
PROJECT_DIR="~/myproject"

tmux has-session -t $PROJECT_NAME 2>/dev/null
if [ "$?" -eq 1 ] ; then
    echo "No Session found.  Creating and configuring."
    pushd $PROJECT_DIR
    tmux new-session -d -s $PROJECT_NAME
    tmux source-file ~/bin/tmux-${PROJECT_NAME}.conf
    popd
else
    echo "Session found.  Connecting."
fi
tmux attach-session -t $PROJECT_NAME

where tmux-myproject.conf is my startup series of tmux commands to create my windows and panes, as well as start my editors.


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.

Tags:

Tmux