Score:4

How can I rejoin my existing tmux session - but if I don't have a session running, create a new one

cn flag

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

Score:2
cn flag

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?

Score:2
vn flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.