How to create or attach to a tmux session in one command?

By Romain Dorgueil

Short answer

tmux new -A -s name

If a session called name already exists, you attach to it; otherwise it is created. No “duplicate session” error either way.

Details

tmux new-session (aliased tmux new) normally fails if the session name is already taken. The -A flag changes that: it makes new-session behave like attach-session when the target already exists.

That single property makes it the right command for anything non-interactive:

  • In a shell startup file (.zshrc, .bashrc) to always land in a named session.
  • In a project script, so the first run creates the session and later runs just re-attach to it.

Add -d to keep it detached — it creates the session without attaching, or does nothing if it is already running:

tmux new -A -d -s name

Verified on tmux 3.2a.