惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
Y
Y Combinator Blog
D
DataBreaches.Net
I
InfoQ
Recent Announcements
Recent Announcements
Last Week in AI
Last Week in AI
G
Google Developers Blog
博客园_首页
博客园 - 司徒正美
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
D
Docker
量子位

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例)
ssh时自动运行tmux
Jiajun Huang · 2019-09-18 · via Jiajun的技术笔记

tmux,终端复用神器,之前我一直用byobu,它是tmux的封装,我看了一下源代码,其实就是一堆的bash脚本+python脚本。因为一些 byobu的bug,我选择使用原生tmux,但是有一个问题,就是以前执行tmux的时候,是在 ~/.bashrc 里加上:

# start tmux
if [[ -z "$TMUX"  ]] && [ "$SSH_CONNECTION" != ""  ]; then
   tmux attach || tmux new
fi

意思就是,当检测到当前是ssh连接并且当前没有使用tmux时,就执行 tmux attach || tmux new,这样就会优先选择连接到上次的 会话,如果没有,那就创建一个新的会话,这样的确也能运行,能在ssh登录时自动运行tmux,但是有一个比较麻烦的缺点,那就是 退出时,由于它是使用一个子进程来执行 tmux attach || tmux new,因此即使退出,我们还是会回到一个没有tmux的连接,也就是说, 我们需要退出两次。解决方案就是写一个脚本,实现和 tmux attach || tmux new 一样的功能,但是使用bash内置的exec替换当前进程 的代码,我用python来实现的:


#!/usr/bin/env python3

import os
import sys
import subprocess


def get_sessions():
    sessions = []

    output = subprocess.Popen(["tmux", "list-sessions"], stdout=subprocess.PIPE).communicate()[0]
    if sys.stdout.encoding is None:
        output = output.decode("UTF-8")
    else:
        output = output.decode(sys.stdout.encoding)
    if output:
        for s in output.splitlines():
            # Ignore hidden sessions (named sessions that start with a "_")
            if s and not s.startswith("_"):
                sessions.append(s.strip())
    return sessions


sessions = get_sessions()
if sessions:
    session_name = sessions[-1].split(":")[0]
    os.execvp("tmux", ["tmux", "attach", "-t", session_name])
else:
    os.execvp("tmux", ["tmux", "new"])

然后把 ~/.bashrc 改成这样的:

# start tmux
if [[ -z "$TMUX"  ]] && [ "$SSH_CONNECTION" != ""  ]; then
    exec ~/.xmonad/bash/tmux.py
fi

注意,要把上面的 ~/.xmonad/bash/tmux.py 替换成你保存 tmux.py 这个脚本的路径,而且记得要给 tmux.py 这个脚本加可执行权限 chmod +x tmux.py

完美!