Tmux cho developer: làm việc hiệu quả hơn trên terminal
SSH vào server, chạy một process dài, rồi terminal disconnect — process chết. Tmux giải quyết vấn đề này và nhiều hơn thế.
Cài đặt
# Ubuntu/Debian
sudo apt install tmux
# macOS
brew install tmux
3 Khái niệm cơ bản
- Session: Một workspace hoàn chỉnh, tồn tại kể cả khi disconnect
-
- Window: Tab trong session
-
- Pane: Chia đôi/ba/bốn một window
Cheat sheet
# Session
tmux new -s dev # Tạo session tên "dev"
tmux ls # Liệt kê sessions
tmux attach -t dev # Attach lại session
tmux kill-session -t dev # Xóa session
Prefix key mặc định: Ctrl+b (viết tắt: C-b)
C-b d → Detach (thoát mà giữ session)
C-b c → Tạo window mới
C-b n → Window tiếp
C-b p → Window trước
C-b 0-9 → Chuyển đến window N
C-b % → Chia pane dọc
C-b " → Chia pane ngang
C-b o → Chuyển pane
C-b x → Đóng pane
C-b z → Zoom pane (toggle full screen)
Setup làm việc điển hình
# Tạo session với layout sẵn
tmux new-session -d -s work
tmux send-keys -t work 'cd ~/project && vim' Enter
tmux split-window -h -t work
tmux send-keys -t work 'cd ~/project' Enter
tmux split-window -v -t work
tmux send-keys -t work 'htop' Enter
tmux attach -t work
Kết quả: 3 panes — editor bên trái, terminal phải trên, htop phải dưới.
Config hữu ích (~/.tmux.conf)
# Đổi prefix từ C-b sang C-a (dễ bấm hơn)
unbind C-b
set -g prefix C-a
bind C-a send-prefix
# Mouse support
set -g mouse on
# Bắt đầu đánh số từ 1 (thay vì 0)
set -g base-index 1
setw -g pane-base-index 1
# Chia pane dễ nhớ hơn
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
# Reload config
bind r source-file ~/.tmux.conf \; display "Config reloaded!"
# Vi mode cho copy
setw -g mode-keys vi
# Tăng history
set -g history-limit 10000
Tmux + SSH = Không mất session
# SSH vào server
ssh server
# Tạo tmux session
tmux new -s deploy
# Chạy deploy script
./deploy.sh
# Detach (C-b d) rồi disconnect SSH
# Ngày hôm sau:
ssh server
tmux attach -t deploy
# Session vẫn còn, output vẫn ở đó
Tmux Resurrect (bonus)
Plugin giữ lại sessions kể cả khi reboot:
# Cài TPM (Tmux Plugin Manager)
git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
# Thêm vào ~/.tmux.conf
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @continuum-restore 'on'
C-b Ctrl+s save, C-b Ctrl+r restore.
Bạn dùng tmux hay screen? Có tip nào hay không?
All rights reserved