Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a session in the background if it doesn't exist but do not attach in tmux

Tags:

shell

tmux

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?

like image 650
Thomas Johnson Avatar asked Oct 16 '14 15:10

Thomas Johnson


People also ask

How do I start a detached tmux session?

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.

How do I create a new tmux session from your current tmux session?

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.

How do I detach all tmux sessions?

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.

How do I know if tmux session is running?

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.


1 Answers

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
like image 99
drizzt Avatar answered Oct 08 '22 03:10

drizzt