4

I use tmux quite a bit, especially on remote servers that I connect to via SSH. I can start a new tmux session by simply running tmux, and I can re-connect to an existing session with tmux a. But, if I run tmux a, and I don't have a session running, it just says this:

$ tmux a
no sessions

That makes sense, as I don't have one running. Is there a way to detect if a session is running, and if there is one already running, connect to it, but if there isn't one running, start a new one?

Unlike this question, I don't care about session names as I don't use them

Artur Meinild
  • 26,018
cocomac
  • 3,394

2 Answers2

2

One possibility is to attempt to re-connect to an existing session, and if that fails (presumably due to there being no sessions), start a new session:

$ tmux a > /dev/null 2>&1; if [[ "$?" == "1" ]]; then tmux; fi

(the > /dev/null 2>&1 hides the no sessions message, "$?" is the exit code, which we check to determine if we need to start a new one)

This appears to work, although it is rather long. Maybe there is a better/shorter way?

NotTheDr01ds
  • 17,888
cocomac
  • 3,394
2

Slightly different and shorter solution: Run tmux ls - if the output is empty create a new session - if not attach.

$ if [[ -z $(tmux ls) ]]; then tmux; else tmux a; fi

Also, maybe this is a bit more logical and easy to understand, since you don't have to consider error redirection and exit codes.

Artur Meinild
  • 26,018