tmux attach to existing sessions or create new ones

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


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.


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

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