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.
I'm not sure since what versione but now you can use
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:tmux ls
and parses the output, looking for something that is not attachedThe command
tmux ls
should return something like this if there are any sessions: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:
and if some were attached and some not, you'd get:
If you find no sessions at all or no free sessions, run
tmux new
to create one. If you find a free session, runtmux 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):
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 =>
will do.
I prefer: "if an un attached tmux session exists, connect to it, else shell" in .profile: