Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a tmux session with multiple windows already opened?

Tags:

bash

tmux

I've tried just about everything I can find online, but nothing is working. I have tried the following methods, and the usual result is a new tmux session with only one window.



Simply in .bashrc.

.bashrc

tmx () {
    tmux new-session -A -s SessionName
    tmux new-window -n Win1
    tmux new-window -n Win2
    tmux new-window -n Win3
    tmux new-window -n Win4
    tmux attach-session -d -t SessionName # with and without this line
    tmux select-window -t Win1 # with and without this line
}


And again only in .bashrc.

.bashrc

tmx () {
    tmux new-session -A -s SessionName ||
    tmux \
        neww -s Win1 \; \
        neww -s Win2 \; \
        neww -s Win3 \; \
        neww -s Win4 \; \
        selectw -t Win1
}


This following attempt would be my preferred method, as it makes the most sense to me.

Calling tmux without the first line makes all the other lines cause a "Session not found" error to occur. This makes no sense, since aren't we supposed to call tmux in order to reach this stuff anyway? My original plan was to make a session and have this file automatically set up my tmux.

.tmux.conf

new-session -A -s SessionName
new-window -t Win1
new-window -t Win2
new-window -t Win3
new-window -t Win4
attach-session -d -t SessionName # with and without this line
select-window -t Win1 # with and without this line


This method, whether using an alias or making a function, usually results in "failed to connect to server". But when fiddling with it enough for that not to happen, it produces the same result as the rest.

.bashrc

alias tmx='tmux source-file "~/.tmux/mysession"'

.tmux/mysession

new-session -A -s SessionName
new-window -t Win1
new-window -t Win2
new-window -t Win3
new-window -t Win4
attach-session -d -t SessionName # with and without this line
select-window -t Win1 # with and without this line


What am I doing wrong?

like image 945
Ness Avatar asked Jan 02 '23 18:01

Ness


1 Answers

You need to create the session in detached mode (-d); otherwise, your script blocks until you detach from the new session. Likewise, your script will block after tmux attach-session until you detach, so you need to select the correct window first. Note that you can -d with new-window to avoid making each new window the current window, eliminating the need to call select-window at all.

Yes, -d gets used a lot.

tmx () {
    # Use -d to allow the rest of the function to run
    tmux new-session -d -s SessionName
    tmux new-window -n Win1
    # -d to prevent current window from changing
    tmux new-window -d -n Win2
    tmux new-window -d -n Win3
    tmux new-window -d -n Win4
    # -d to detach any other client (which there shouldn't be,
    # since you just created the session).
    tmux attach-session -d -t SessionName
}
like image 129
chepner Avatar answered Jan 23 '23 09:01

chepner