I've looked at this similar question which asks about creating a tmux
session, or attaching if it doesn't exist.
What I'd like to do is a little different: create a tmux
session if it doesn't exist, but don't attach. The plan is to create a few different sessions with canonical names, then send commands to them using tmux send
. Is there an easy way in tmux
or shell scripting to create a session with a specific name only if it doesn't exist?
Use the 'tmux ls' command to view all the sessions: Now we will use the combination 'Prefix+D' and see what happens: As we can see now, it asks to select the session we want to detach. Use the arrows to select the session and hit enter to detach it.
Using the Prefixes to Control Tmux By default, the prefix is CTRL+B. That is, we have to press the keys CTRL+B and then the command. For example, to create a new session, the command would be C. So, to create a new session we need to press CTRL+B and next C – CTRL+B, C.
In a tmux session, tmux detach-client -a will detach all other clients except the current one. So you can simply call detach_others from your terminal, and all other sessions will be detached.
To enter command mode, type prefix>: followed by list-sessions or ls to view a list of currently active Tmux sessions. By default, list-sessions are bound to the prefix> s key combination. With j and k, you may explore the session list and activate one by hitting enter.
If you try to create a session with the same name tmux returns an error with exit code 1.
drizzt@liara ~ % tmux new-session -d -s test
drizzt@liara ~ % tmux new-session -d -s test
duplicate session: test
drizzt@liara ~ % echo $?
1
drizzt@liara ~ %
If you don't like the duplicate session error you can do something like:
drizzt@liara ~ % tmux has-session -t test || tmux new-session -d -s test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With