Skip to content
shellhacks.dev
Tooling

Attach or create in one command

Attach to a tmux session if it exists and create it otherwise with tmux new-session -A -s name. In a script without a terminal use has-session instead.

1 min read
Summarize in AI

A shell alias should give you your session whether or not one is already running.

Shell
tmux new-session -d -s main
tmux new-session -d -s main; echo "plain, second time: $?"
tmux new-session -A -s main; echo "with -A and no terminal: $?"
tmux has-session -t main 2>/dev/null || tmux new-session -d -s main
tmux ls -F '#{session_name}'
Text
duplicate session: main
plain, second time: 1
open terminal failed: not a terminal
with -A and no terminal: 1
main

-A makes new-session behave like attach-session when the named session exists, and like a normal create when it does not, as the tmux manual says. The second command shows what a plain create does with a name that is taken: it fails with "duplicate session". The third run has no terminal, so the attach half of -A fails. In a real terminal that same command is the whole alias. The has-session line is the form for a script, and the listing shows one session.

-A needs a terminal to attach to, so use it in a shell alias and never in cron or CI. Adding -d to it detaches the other clients that are attached, which can surprise a colleague sharing the session. A command given after the session name is ignored when the session already exists.

Share

More snippets

Tooling

Swap two panes in a window

Swap two panes in a window with swap-pane -s source -t target. The panes keep their IDs and running programs and trade positions, and prefix then braces do it.

2 min read
Tooling

Resize a pane

Resize a pane with resize-pane -x 30 for an exact width or -R 10 to move its edge. The keys are prefix then Ctrl and an arrow, one cell at a time.

1 min read
Tooling

Zoom a pane to full screen

Zoom one pane to fill the window with resize-pane -Z, or prefix then z, and call it again to restore. The window shows a Z flag while zoomed.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.