How to create new tmux session if none exists

tmux

I am trying to figure out how to attach to a tmux session if a named tmux session exists, if not I want to create a new one with the given name.

Currently, I know of a few tmux commands which can partly achieve what I am looking for, but its not clear how to combine them together to get what I am looking for:

  • tmux attach attaches to an automatically existing session – but errors out if no session exists
  • tmux new creates a new session – but it does so every time, so I can't leave it in my .tmux.conf
  • tmux has-session tests whether a session exists – but I don't know how to stitch it together with the other commands

Thus, I would like to create a tmux script, so that this happens automatically, instead of having to manually create it everytime I need to log into a sessions.

How can I write a automatic script so as to create a new tmux session (if a given session name doesnt exist) or attach to a session name (if it exists)?

Best Answer

I figured it out (and had it pointed out to me).

tmux attach || tmux new
Related Topic