如何创建一个已打开多个 windows 的 tmux 会话?

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

我已经尝试了几乎所有可以在网上找到的方法,但没有任何效果。我尝试了以下方法,通常的结果是一个只有一个 window.

的新 tmux 会话

只需在 .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
}


同样仅在 .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
}


以下尝试是我的首选方法,因为它对我来说最有意义。

在没有第一行的情况下调用 tmux 会使所有其他行导致发生 "Session not found" 错误。这是没有意义的,因为我们不应该调用 tmux 来获取这些东西吗?我最初的计划是建立一个会话并让这个文件自动设置我的 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


这种方法,无论是使用别名还是制作函数,通常都会得到"failed to connect to server"。但是当对它进行足够的调整以防止这种情况发生时,它会产生与其他结果相同的结果。

.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


我做错了什么?

您需要在分离模式下创建会话(-d);否则,您的脚本会阻塞,直到您从新会话中分离出来。同样,您的脚本将在 tmux attach-session 之后阻塞,直到您分离,因此您需要先 select 正确的 window。请注意,您可以 -dnew-window 以避免将每个新的 window 变成当前的 window,从而完全不需要调用 select-window

是的,-d 经常使用。

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
}