151

I am trying to figure out how to attach to a tmux session if a named tmux session exists, if not I want to create a new one with the given name.

Currently, I know of a few tmux commands which can partly achieve what I am looking for, but its not clear how to combine them together to get what I am looking for:

  • tmux attach attaches to an automatically existing session - but errors out if no session exists
  • tmux new creates a new session - but it does so every time, so I can't leave it in my .tmux.conf
  • tmux has-session tests whether a session exists - but I don't know how to stitch it together with the other commands

Thus, I would like to create a tmux script, so that this happens automatically, instead of having to manually create it everytime I need to log into a sessions.

How can I write a automatic script so as to create a new tmux session (if a given session name doesnt exist) or attach to a session name (if it exists)?

8
  • 15
    @kzh: I view it as a programming tool question, like vim
    – rampion
    Jan 21, 2011 at 18:46
  • 6
    I have written another possible answer for this question as a gist, in case anyone's interested: gist.github.com/chakrit/5004006
    – chakrit
    Feb 21, 2013 at 11:22
  • 10
    Meanwhile, my man tmux says: "The -A flag makes new-session behave like attach-session if session-name already exists" Nov 18, 2013 at 13:13
  • 1
    For those flagging to move this, I should note that even moderators cannot migrate questions more than 60 days old to another site. The reasons for this system limit are explained here.
    – Brad Larson
    Feb 21, 2017 at 3:22
  • 1
    @BradLarson, currently, the best/simplest option to do this is answered in a comment, way down: stackoverflow.com/questions/3432536/…. Most users who come here wont be able to find this. This is obviously a very important question as you can see by the number of votes. Is it possible to open this question, so I can add that as an answer, so new people can find this?
    – alpha_989
    Mar 6, 2018 at 13:33

7 Answers 7

168

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

tmux attach || tmux new
9
  • 29
    This answer works better for me because I can name the session: tmux attach-session -t my-session || tmux new-session -s my-session. The only problem is this is not atomic. tmux really ought to have a create-or-attach command.
    – Andrew
    May 11, 2012 at 20:19
  • 5
    I have next alias in bash - alias tm='tmux attach || tmux new'
    – azat
    Apr 17, 2013 at 19:51
  • 10
    Upvoting because with a small tweak this works with named sessions: tmux attach -t some_name || tmux new -s some_name. Change some_name to $1 add a shebang, and save. Jan 9, 2014 at 4:48
  • 11
    Note to those unfamiliar with tmux and wondering about new vs new-session: they are synonyms, and so are attach and attach-session.
    – Esteis
    Jul 24, 2015 at 8:38
  • 1
    tmux new-session -ds default \; split-window -dv 2>/dev/null; tmux attach -t default works far better and does not open a second tmux in case you /bin/kill the first one. The only downside is that you need to name the sessions for this.
    – Tino
    May 25, 2016 at 16:05
90

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.

6
  • 3
    When this creates a new session, the default path is my home directory, not the path from which tmux was invoked. Sep 14, 2011 at 22:31
  • 2
    @A.B: which answer do you mean? Jun 15, 2012 at 13:58
  • Is there a way to make this solve @RichardHansen's issue? Invoking from the current path seems to make the most sense, and if new-session destroys that then it seems to be a real issue. Sep 29, 2013 at 16:50
  • 2
    This breaks the tmux config reloading in case you use it (source-file ~/.tmux.conf) Dec 15, 2015 at 15:52
  • 11
    @SebastianBlask you can use the -A option to new-session if you name your session. new-session -A -s mysession will play nicely with config reloading.
    – jkoelker
    Mar 22, 2016 at 6:22
90

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.

1
  • 1
    If you are going to use this in something like gnome-terminal as the command I'd suggest leaving off the -s and the specific session name so you don't end up with EVERY new gnome-terminal session attached to the same session. You can always select an existing session with prefix + s after opening a new terminal.
    – dragon788
    Jul 4, 2018 at 3:58
15

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.

14

Although I find rampion's answer is sufficient for using 1 session, this script lets you setup multiple sessions:

SESSIONS="work play"

function has-session {
    tmux has-session -t $1 2>/dev/null
}

function except 
{
    if [ "$?" -eq 1 ] ; then
        $1
    fi
}

# Configure your sessions here
function session-work
{
    tmux new-session -d -s work
    tmux neww -k -t work:1
}

function session-play
{
    tmux new-session -d -s play
    tmux neww -k -t play:1
}

#
#MAIN 
for x in $SESSIONS
do
    echo $x
    has-session $x
    except session-$x
done

NOTE:

-k  --> new-window will not be created if already exists
-d  --> start session or window, but don't attach to it yet
-s  --> name the session
-t  --> specify a target location in the form session:window.pane 
9

I use an alias to create a new session if needed, and attach to my default session if it already exists:

alias tmuxre='tmux new-session -t default || tmux new-session -s default'

I added this to my .login on my server.

The reason I do it this way is because I don't want to attach to the same actual session, I want a new session which uses the same group of windows.

This is also similar to running screen -xRR.

7
  • 2
    If you are in and out of your session often, this leaves lots of unused sessions, as seen by tmux list-sessions.
    – Anm
    Aug 16, 2012 at 19:09
  • Yeah, it does, I just clean them up every now and then. It's a minor drawback to get the functionality I want.
    – Michael
    Aug 23, 2012 at 21:49
  • Hey @mateusz-piotrowski - I agree with the edit to wrap my code in a code block but why would you edit the other text to be different than what I said? Sorry to comment here but I didn't see anywhere else to.
    – Michael
    Jan 25, 2016 at 23:02
  • I didn't mean to offend you. I just thought you couldn't run an alias in a config file and so it must have been a typo. Jan 25, 2016 at 23:08
  • 3
    By now, you can just type: tmux new -A -s default to launch a new session if it is not exist or attach automatically. I think it's much better than editing config file.
    – pjincz
    Apr 25, 2017 at 7:56
2

For those who want to do the same thing in fish:

tmux attach -t mysesh; or tmux new -s mysesh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.