I am trying to figure out how to attach to a tmux session
if a named tmux session exists, if not I want to create a new one with the given name.
Currently, I know of a few tmux
commands which can partly achieve what I am looking for, but its not clear how to combine them together to get what I am looking for:
tmux attach
attaches to an automatically existing session - but errors out if no session existstmux new
creates a new session - but it does so every time, so I can't leave it in my .tmux.conf
tmux has-session
tests whether a session exists - but I don't know how to stitch it together with the other commandsThus, I would like to create a tmux script, so that this happens automatically, instead of having to manually create it everytime I need to log into a sessions.
How can I write a automatic script so as to create a new tmux session (if a given session name doesnt exist) or attach to a session name (if it exists)?
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.
All the commands you can launch within your terminal, like tmux new -s sessionName can be launched from within tmux by pressing the trigger key (eg: ctrl-b ) then : then the command without the starting tmux part.
The Tmux kill-session command is used to kill a Tmux session. Tmux will terminate the current or last active session if no session is specified. Depending on whether or not you are currently in an active Tmux session. The -t option, with the session name as its argument, can be used to specify a session to kill.
To configure your terminal to automatically start tmux as default, add the following lines to your ~/. bash_profile shell startup file, just above your aliases section. Save the file and close it. Then close and reopen the terminal to start using tmux by default, every time you open a terminal window.
I figured it out (and had it pointed out to me).
tmux attach || tmux new
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