組み込みProgrammerのチラシの裏

Tmux sessionをOS再起動後に再構築する

| Comments

OS再起動後にtmux sessionを毎回作成するのが大変だったため調査。 エディタの状態などはemacsが覚えているため問題ないが、tmux管理のtabとディレクトリぐらいは再構築してほしかった。

superuser.com > Restore tmux session after reboot を参考に構築。

使い方

tmux session保存時

1
$ phoenix_tmux_session save

再起動時(tmux session再構築)

1
$ phoenix_tmux

設定方法

2個のファイルを作成する

  • $HOME/bin/phoenix_tmux_session : tmux sessionをsave/restoreする
  • $HOME/bin/phoenix_tmux : セッション「phoenix」があればアタッチ。なければ作成/restore/アタッチ。

$HOME/bin/phoenix_tmux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/zsh

# @see
# https://superuser.com/questions/440015/restore-tmux-session-after-reboot
# https://github.com/mislav/dotfiles/blob/d2af5900fce38238d1202aa43e7332b20add6205/bin/tmux-session

SESSIONNAME="phoenix"
tmux has-session -t $SESSIONNAME &> /dev/null

if [ $? != 0 ]; then
    tmux new-session -s $SESSIONNAME -d
    phoenix_tmux_session restore
fi

tmux attach -t $SESSIONNAME

$HOME/bin/phoenix_tmux_session

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env bash
# Save and restore the state of tmux sessions and windows.
# TODO: persist and restore the state & position of panes.

# @see
# https://superuser.com/questions/440015/restore-tmux-session-after-reboot
# https://github.com/mislav/dotfiles/blob/d2af5900fce38238d1202aa43e7332b20add6205/bin/tmux-session

set -e

dump() {
  local d=$'\t'
  tmux list-windows -a -F "#S${d}#W${d}#{pane_current_path}"
}

save() {
  dump > ~/.tmux-session
}

terminal_size() {
  stty size 2>/dev/null | awk '{ printf "-x%d -y%d", $2, $1 }'
}

session_exists() {
  tmux has-session -t "$1" 2>/dev/null
}

add_window() {
  tmux new-window -d -t "$1:" -n "$2" -c "$3"
}

new_session() {
  cd "$3" &&
  tmux new-session -d -s "$1" -n "$2" $4
}

restore() {
  tmux start-server
  local count=0
  local dimensions="$(terminal_size)"

  while IFS=$'\t' read session_name window_name dir; do
    if [[ -d "$dir" && $window_name != "log" && $window_name != "man" ]]; then
      if session_exists "$session_name"; then
        add_window "$session_name" "$window_name" "$dir"
      else
        new_session "$session_name" "$window_name" "$dir" "$dimensions"
        count=$(( count + 1 ))
      fi
    fi
  done < ~/.tmux-session

  echo "restored $count sessions"
}

case "$1" in
save | restore )
  $1
  ;;
* )
  echo "valid commands: save, restore" >&2
  exit 1
esac

Comments