8

I am looking for a ssh / tmux solution that would act like this:

  • if there is no session, create one
  • if there is a session and nobody is connected to it, create another one

Mainly I want to be able to create new sessions to the same server, obviously if there is more than one session that has nobody connected to it, it should pick the first one.

This should enable me to put this as default command for ssh connections.

My current solution ssh -t 'tmux a || tmux || /bin/bash' doesn't work as expected because when you try to connect again it will connect to the existing session, and in this case I want a new one.

sorin
  • 8,454

4 Answers4

14

I'm not sure since what versione but now you can use

tmux new -A -s <session-name>

The -A flag makes new-session behave like attach-session if session-name already exists

Edo
  • 241
2

That's kind of an odd use-case, but what you'd need to do is write a wrapper around tmux (call it mytmux or something) that:

  1. calls tmux ls and parses the output, looking for something that is not attached
  2. attach to the first non-attached session, -OR-
  3. create a session if no free sessions are found and attach to it

The command tmux ls should return something like this if there are any sessions:

<~> $ tmux ls
0: 1 windows (created Mon Sep 16 21:42:16 2013) [120x34] (attached)

where the initial field ('0') is the session name and the last field denotes whether anyone is attached to it. So if no one was attached it would look like this:

<~> $ tmux ls
0: 1 windows (created Mon Sep 16 21:42:16 2013) [120x34]

and if some were attached and some not, you'd get:

<~> $ tmux ls
0: 1 windows (created Mon Sep 16 21:42:16 2013) [120x34] (attached)
1: 1 windows (created Mon Sep 16 21:43:30 2013) [120x34]

If you find no sessions at all or no free sessions, run tmux new to create one. If you find a free session, run tmux attach -t 1 where '1' is the name of the free session.

1

I also needed the 're-use any detached session or create one' feature. Here's my one-liner for this (will fail miserably if you use ":" in session name):

tmux attach -t $(tmux ls | grep -v attached | head -1 | cut -f1 -d:) || tmux
1

The OP's post is a bit confusing but from the original solution "tmux a || tmux || bash" I deduct: attach to existing or create new one =>

tmux ls | grep -v attached && tmux attach || tmux

will do.

I prefer: "if an un attached tmux session exists, connect to it, else shell" in .profile:

tmux ls | grep -v attached && tmux attach

thilo
  • 111