晴耕雨読

working in the fields on fine days and reading books on rainy days

tmuxの使い方

ターミナルマルチプレクサ tmux を使うと、1つのssh接続で複数のシェルを立ち上げられます。 さらに、ssh中にネットワークが切断されても、プロセスはサーバ側で動き続けるので、再開することができます。

tmux 使用時にネットワークを切断してみる

sshで接続して、tmuxをインストールして起動します。

$ ssh local1
$ sudo yum install tmux
$ tmux

1秒ごとにカウントアップする処理を実行します。

$ c=0; while true; do c=$(expr $c + 1); echo $c; sleep 1; done
1
2
3
...

突然接続を切るために、端末のウィンドウを閉じます。 「このウィンドウで実行中のプロセスを終了しますか」と警告されますが、そのまま終了します。

そしたら、再度sshで接続します。

$ ssh local1

起動中のプロセスを確認すると、1秒ごとにカウントアップする処理が残っていることがわかります。

$ px auxwf
...
root      3887  0.0  0.0  22348  1800 ?        Ss   19:07   0:00 tmux
root      3888  0.0  0.1 115440  2036 pts/1    Ss   19:07   0:00  \_ -bash
root      4258  0.0  0.0 107952   356 pts/1    S+   19:10   0:00      \_ sleep 1

作業中の全てのウィンドウに戻ります。

$ tmux attach
...
214
215
216

ネットワークが切断されてもプロセスは動き続けていることが確認できました。


コマンド上でのセッション操作

操作 コマンド
セッションの作成 tmux, tmux new
名前を付けて作成 tmux new -s mysession
セッションの削除 tmux kill-session -t mysession
現在のセッション以外を削除 tmux kill-session -a
セッションの一覧表示 tmux ls
セッションを再開 tmux attachtmux a
名前指定でセッションを再開 tmux attach -t mysessiontmux a -t mysession

セッション操作 (Sessions)

操作 キーボード
セッションの一覧表示と選択 Ctrl+b, s (Select)
セッションから離脱 Ctrl+b, d (Detach)
セッション名の変更 Ctrl+b, $

ウィンドウ操作 (Windows)

操作 キーボード
ウィンドウの作成 Ctrl+b, c (Create)
ウィンドウの切り替え Ctrl+b, n (Next)、Ctrl+b, p (Previous)
ウィンドウの一覧選択 Ctrl+b, w (Window)
ウィンドウの移動 Ctrl+b, 0-9
以前のウィンドウに移動 Ctrl+b, l (Latest)
ウィンドウ名の変更 Ctrl+b, ,

ペイン操作 (Panes)

操作 キーボード
左右分割 Ctrl+b, %
上下分割 Ctrl+b, "
ペインを閉じる Ctrl+b, X (Exit)
次のペインに移動 Ctrl+b, o
ペイン間の移動 Ctrl+b, 矢印
以前のペインに移動 Ctrl+b, ;
レイアウトの変更 Ctrl+b, Space
ペインを移動 Ctrl+b, {Ctrl+b, }
ペインの最大化/元に戻す Ctrl+b, z (Zoom)
ペインをウィンドウ化 Ctrl+b, !
ペイン番号の表示 Ctrl+b, q
ペイン番号の表示と選択 Ctrl+b, q, 0-9

コピーモード (Copy Mode)

setw -g mode-keys vi で vi モードの操作にする。

操作 キーボード
コピーモード開始 Ctrl+b, [
コピーモード終了 q
コピー開始位置決定 Space
コピー開始位置決定 Enter
カーソル移動 h j k l
貼り付け Ctrl+b, ]

その他 (Misc)

操作 キーボード
コマンドモードに切り替え Ctrl+b, :
全てのセッションへの設定 : set -g OPTION
全てのウィンドウへの設定 : setw -g OPTION

設定ファイル

設定ファイルは ~/.tmux.conf に配置します。 編集してすぐに反映させたいときは tmux source ~/.tmux.conf を実行します。

tmux設定ファイルのサンプル:

# 設定ファイルをリロードする
bind r source-file ~/.tmux.conf \; display "Reloaded!"

# | でペインを縦に分割する
bind | split-window -h
# - でペインを横に分割する
bind - split-window -v

# Vimのキーバインドでペインを移動する
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# Vimのキーバインドでペインをリサイズする
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5

# 256色端末を使用する
set -g default-terminal "screen-256color"

# キーストロークのディレイを減らす (Escキーの反応を速くする)
set -sg escape-time 1

# マウス操作を有効にする
setw -g mouse on

# --- コピーモードの設定 ---

# viのキーバインドを使用する
setw -g mode-keys vi
# クリップボードへのコピー
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy" # MacOS
# 範囲を選択しながらyを押すとクリップボードにコピーされる

参考文献