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 create the session detached:
tmux new -A -d -s name
One trap: -d only applies when the session gets created. If it already exists, -A switches
to attach behaviour and the command attaches anyway; in a script with no terminal it fails with
open terminal failed: not a terminal. For a strict create-if-missing, guard the call instead:
tmux has-session -t name 2>/dev/null || tmux new -d -s name
Verified on tmux 3.2a.