【实用工具】使用 tmux 保存和恢复会话
动机
在日常开发中,我会使用 Tmux 来管理多个终端窗口和会话。而如果服务器重启,通常需要重新手动建立会话。tmux-resurrect 和 tmux-continuum 这两个插件的组合可以让你:
- tmux-resurrect: 手动保存和恢复 tmux 会话
- tmux-continuum: 自动保存会话,并在 tmux 启动时自动恢复
两者结合使用,可以实现真正的”无缝工作”体验——即使系统重启,你的工作环境也能完整恢复。
安装
1. 安装 TPM (Tmux Plugin Manager)
首先需要安装 tmux 插件管理器:
1 | git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm |
2. 配置 ~/.tmux.conf
1 | vi ~/.tmux.conf |
在末尾添加以下配置:
1 | # 插件列表 |
3. 安装插件
在 tmux 会话中执行以下操作:
重新加载配置:
1
tmux source ~/.tmux.conf
安装插件:按
Ctrl + b然后按Shift + I(大写 I)- 稍等几秒钟,会看到提示:”TMUX environment reloaded. Done, press ESCAPE to continue.”
- 按
ESC键退出
检查安装状态:
1
ls ~/.tmux/plugins/
使用
Resurrect 需要手动操作
手动保存所有会话: 在任意 tmux 会话中:
Ctrl + b→Ctrl + s- 底部显示:”Tmux environment saved!”
手动恢复所有会话:
Ctrl + b→Ctrl + r- 底部显示:”Tmux restore complete!”
Continuum 则会自动操作
- ✅ 每 15 分钟自动保存一次会话
- ✅ Tmux 启动时自动恢复上次的会话
- ✅ 在状态栏显示保存状态
查看保存状态
在状态栏右侧会显示 Continuum 的状态:
- 显示距离上次保存的时间
- 或显示 “off” 如果自动保存被禁用
其他配置
自定义恢复的程序
默认情况下,resurrect 会恢复大多数程序,但你可以自定义:
1 | # 恢复更多程序 |
更新插件
在 tmux 会话中按 Ctrl + b → U(大写 U),选择要更新的插件。
卸载
如果需要卸载插件:
- 从
~/.tmux.conf中删除相关配置 - 删除插件目录:
1
2rm -rf ~/.tmux/plugins/tmux-resurrect
rm -rf ~/.tmux/plugins/tmux-continuum - 重新加载配置:
tmux source ~/.tmux.conf
参考资源
- tmux-resurrect GitHub: https://github.com/tmux-plugins/tmux-resurrect
- tmux-continuum GitHub: https://github.com/tmux-plugins/tmux-continuum
- TPM GitHub: https://github.com/tmux-plugins/tpm
评论