如果不存在,如何创建新的 tmux 会话

发布于 2024-09-13 04:32:58 字数 505 浏览 8 评论 0原文

我试图弄清楚如果存在命名的 tmux 会话,如何附加到 tmux 会话,如果不存在,我想创建一个具有给定名称的新会话。

目前,我知道一些 tmux 命令可以部分实现我正在寻找的东西,但不清楚如何将它们组合在一起以获得我正在寻找的东西:

  • tmux Attach 附加到自动存在的会话 - 但如果不存在会话,则会出错
  • tmux new 创建一个新会话 - 但它每次都会这样做,所以我不能将其留在我的 中。 tmux.conf
  • tmux has-session 测试会话是否存在 - 但我不知道如何将其与其他命令拼接在一起

因此,我想创建一个 tmux 脚本,这样这会自动发生,而不必每次需要登录会话时手动创建它。

如何编写自动脚本来创建新的 tmux 会话(如果给定的会话名称不存在)或附加到会话名称(如果存在)?

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 exists
  • tmux 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 commands

Thus, 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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

懒猫 2024-09-20 04:32:58

我弄清楚了(并向我指出了< /a>)。

tmux attach || tmux new

I figured it out (and had it pointed out to me).

tmux attach || tmux new
一杆小烟枪 2024-09-20 04:32:58

正如 的评论中指出的那样彼得·维克托林jkoelkerpjincz ,您可以使用以下命令附加到 mySession(如果存在),如果不存在则创建它:

 tmux new -A -s mySession

来自 man tmux

新会话[-AdDEP] [-c开始目录] [-F格式] [-n窗口名称] [-s会话名称] [-t组名称] [-x宽度] [-y高度] [shell命令]

(别名:

创建一个名为session-name的新会话。

[...]

-A 标志使 new-session 的行为类似于 attach-session 如果会话名称已经存在;在这种情况下,-D 的行为类似于 attach-session-d

new-session 已支持-A 自 tmux-1.8 起。

As pointed out in comments from Petr Viktorin, jkoelker and pjincz, you can use the following command to attach to mySession if it exists, and to create it if it doesn't:

 tmux new -A -s mySession

From man tmux:

new-session[-AdDEP] [-cstart-directory] [-Fformat] [-nwindow-name] [-ssession-name] [-tgroup-name] [-xwidth] [-yheight] [shell-command]

(alias: new)

Create a new session with name session-name.

[...]

The -A flag makes new-session behave like attach-session if session-name already exists; in this case, -D behaves like -d to attach-session.

new-session has supported -A since tmux-1.8.

盗心人 2024-09-20 04:32:58

或者,您可以添加

new-session

.tmux.conf - 这将在服务器启动时创建默认会话。

然后 tmux Attach 将附加到当前会话(即正在运行的服务器),或者创建一个新会话(启动服务器,读取配置文件,发出 new-session代码>命令)并附加到它。

Alternately, you can add

new-session

to your .tmux.conf - that will create a default session on server start.

Then tmux attach will either attach to the current session (running server, that is), or create a new session (start the server, read the config file, issue the new-session command) and attach to that.

故事与诗 2024-09-20 04:32:58

根据 Alex 的建议,在启动时包含基于项目的配置,我开始使用以下内容:

# ~/bin/tmux-myproject shell script
# The Project name is also used as a session name (usually shorter)
PROJECT_NAME="myproject"
PROJECT_DIR="~/myproject"

tmux has-session -t $PROJECT_NAME 2>/dev/null
if [ "$?" -eq 1 ] ; then
    echo "No Session found.  Creating and configuring."
    pushd $PROJECT_DIR
    tmux new-session -d -s $PROJECT_NAME
    tmux source-file ~/bin/tmux-${PROJECT_NAME}.conf
    popd
else
    echo "Session found.  Connecting."
fi
tmux attach-session -t $PROJECT_NAME

其中 tmux-myproject.conf 是我的启动系列 tmux 命令,用于创建窗口和窗格,以及启动编辑器。

Adapting Alex's suggestion to include project based configuration upon startup, I started using the following:

# ~/bin/tmux-myproject shell script
# The Project name is also used as a session name (usually shorter)
PROJECT_NAME="myproject"
PROJECT_DIR="~/myproject"

tmux has-session -t $PROJECT_NAME 2>/dev/null
if [ "$?" -eq 1 ] ; then
    echo "No Session found.  Creating and configuring."
    pushd $PROJECT_DIR
    tmux new-session -d -s $PROJECT_NAME
    tmux source-file ~/bin/tmux-${PROJECT_NAME}.conf
    popd
else
    echo "Session found.  Connecting."
fi
tmux attach-session -t $PROJECT_NAME

where tmux-myproject.conf is my startup series of tmux commands to create my windows and panes, as well as start my editors.

探春 2024-09-20 04:32:58

虽然我发现 Rampion 的答案足以使用 1 个会话,但此脚本允许您设置多个会话:

SESSIONS="work play"

function has-session {
    tmux has-session -t $1 2>/dev/null
}

function except 
{
    if [ "$?" -eq 1 ] ; then
        $1
    fi
}

# Configure your sessions here
function session-work
{
    tmux new-session -d -s work
    tmux neww -k -t work:1
}

function session-play
{
    tmux new-session -d -s play
    tmux neww -k -t play:1
}

#
#MAIN 
for x in $SESSIONS
do
    echo $x
    has-session $x
    except session-$x
done

注意:

-k  --> new-window will not be created if already exists
-d  --> start session or window, but don't attach to it yet
-s  --> name the session
-t  --> specify a target location in the form session:window.pane 

Although I find rampion's answer is sufficient for using 1 session, this script lets you setup multiple sessions:

SESSIONS="work play"

function has-session {
    tmux has-session -t $1 2>/dev/null
}

function except 
{
    if [ "$?" -eq 1 ] ; then
        $1
    fi
}

# Configure your sessions here
function session-work
{
    tmux new-session -d -s work
    tmux neww -k -t work:1
}

function session-play
{
    tmux new-session -d -s play
    tmux neww -k -t play:1
}

#
#MAIN 
for x in $SESSIONS
do
    echo $x
    has-session $x
    except session-$x
done

NOTE:

-k  --> new-window will not be created if already exists
-d  --> start session or window, but don't attach to it yet
-s  --> name the session
-t  --> specify a target location in the form session:window.pane 
爱冒险 2024-09-20 04:32:58

如果需要,我使用别名创建一个新会话,如果它已经存在,则附加到我的默认会话:

alias tmuxre='tmux new-session -t default || tmux new-session -s default'

我将其添加到我服务器上的 .login 中。

我这样做的原因是因为我不想附加到同一个实际会话,我想要一个使用同一组窗口的新会话。

这也类似于运行 screen -xRR 。

I use an alias to create a new session if needed, and attach to my default session if it already exists:

alias tmuxre='tmux new-session -t default || tmux new-session -s default'

I added this to my .login on my server.

The reason I do it this way is because I don't want to attach to the same actual session, I want a new session which uses the same group of windows.

This is also similar to running screen -xRR.

緦唸λ蓇 2024-09-20 04:32:58

对于那些想在 fish 中做同样事情的人:

tmux attach -t mysesh; or tmux new -s mysesh

For those who want to do the same thing in fish:

tmux attach -t mysesh; or tmux new -s mysesh
GRAY°灰色天空 2024-09-20 04:32:58

(编辑:本答案末尾提到了考虑命名会话的解决方案)

我在寻找特定用例时遇到了这个问题,但找不到任何解决方案,所以我将在此处添加我的解决方案:

在终端启动 tmux 时,应该:

  • 检查是否有任何未附加的会话,并使用它能找到的第一个会话(每个会话仅附加一次)
  • 如果没有未附加的会话,则创建一个新会话

阅读 tmux 手册页并在 bash 中查找数组我能够想出以下一行:

 tmux attach -t ${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new

解释:

  • tmux Attach -t $A
    使用变量 A 的内容附加到会话(在我们的例子中是列表会话命令 + 数组索引调用的返回值)

  • tmux new
    创建新会话

  • -> tmux Attach -t $A || tmux 新
    如果 tmux Attach 失败,则创建一个新会话

下一部分(我们的 $A)是查找未附加的会话:

  • A = ${$B[1]}:返回列表 B 中的第二个元素(第一个似乎总是空字符串)
  • B = tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}'
    • tmux list-sessions:列出所有会话
    • tmux list-sessions -F '#{session_name}:-F 代表格式,-F '#{session_name}' 告诉 tmux 仅显示名称输出列表时只显示会话的内容
    • tmux list-sessions -f '#{==:#{session_attached},0}':-f 代表过滤器,-f '#{==:#{ session_attached},0}'告诉 tmux 仅显示那些 session_attached 值等于 0 的列表元素
    • tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}':两个标志组合将仅输出会话名称和仅适用于列表中 session_attached 值等于 0(=未附加会话)的元素

示例:

我的应用程序适用于 WSL,因此我添加了它用于在 Windows 终端的 settings.json 中启动我的 Ubuntu 配置文件:

"commandline": "C:\\Windows\\system32\\wsl.exe -d Ubuntu-22.04 tmux Attach -t ${$ (tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new",

编辑:
如果您有 ([a-zA-Z]) 命名会话,您可以对列表进行排序,将它们放在开头:
tmux Attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached}, 0}')[*]}")[1]} || tmux new

如果您在上一个命令的开头添加 tmux new -s "primary" || ,它将尝试创建名为“primary”的会话(如果该会话已存在)如果它仍然未附加,它只会附加到它,否则它将使用另一个未附加会话(命名优先于未命名),或者如果没有剩余未附加会话,则仅创建一个新的未命名会话。

注意:每次运行此命令并且“primary”已经存在时,它都会输出一条错误消息,表明无法创建名为“primary”的会话(仅瞬间可见)

编辑编辑:
您可以使用 &> 重定向这些消息/dev/null

(tmux new -s primary || tmux new -s secondary || tmux new -s tertiary)  &> /dev/null || tmux attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[*]}")[1]} || tmux new"

(edit: A solution considering named sessions is mentioned at the end of this answer)

I came across this question when I was looking for a particular use-case, but couldn't find any solutions to it, so I'll add mine here:

Upon terminal-launch tmux should:

  • check whether there are any unattached sessions and use the first it can find (each session will be attached only once)
  • if there are no unattached sessions create a new one

After reading through the tmux man-pages and looking up arrays in bash I was able to come up with the following one-liner:

 tmux attach -t ${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new

Explanation:

  • tmux attach -t $A:
    attach to session with content of variable A (in our case the return value of the list-session command + array-index call)

  • tmux new:
    create new session

  • together -> tmux attach -t $A || tmux new:
    if tmux attach fails, create a new session

The next part (our $A) is finding an unattached session:

  • A = ${$B[1]}: return the second element in the list B (first one seems to always be an empty string)
  • B = tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}'
    • tmux list-sessions: list all sessions
    • tmux list-sessions -F '#{session_name}: -F stands for format and -F '#{session_name}' tells tmux to only show the name of the session and nothing else when it outputs the list
    • tmux list-sessions -f '#{==:#{session_attached},0}': -f stands for filter and -f '#{==:#{session_attached},0}'tells tmux to show only those list-elements, where the session_attached-value is equal to 0
    • tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}': both flags in combination will output only the session name and only for those elements of the list, where the session_attached-value is equal to 0 (=unattached sessions)

Example:

My application was for WSL, so I added it to the launch of my Ubuntu profile inside the settings.json of Windows Terminal:

"commandline": "C:\\Windows\\system32\\wsl.exe -d Ubuntu-22.04 tmux attach -t ${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[1]} || tmux new",

Edit:
If you have ([a-zA-Z]) named sessions you can sort the list to put those at the beginning:
tmux attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[*]}")[1]} || tmux new

If you add tmux new -s "primary" || at the beginning of the previous command it will try to create the session with the name "primary" and if it already exists it will only attach to it if it is still unattached, otherwise it will take another unattached session (prioritizing named over unnamed) or just create a new unnamed session if there are no unattached sessions left.

Caveat: each time you run this command and "primary" already exists it will output an error-message that it wasn't able to create a session called "primary" (only visible for a split second)

edit edit:
you can redirect those messages by using &> /dev/null:

(tmux new -s primary || tmux new -s secondary || tmux new -s tertiary)  &> /dev/null || tmux attach -t ${$(sort -n <<<"${$(tmux list-sessions -F '#{session_name}' -f '#{==:#{session_attached},0}')[*]}")[1]} || tmux new"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文