aboutsummaryrefslogtreecommitdiff
path: root/wtmux
blob: 38532826603420ec85977ec872d8ee59a5748e3f (plain)
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
64
65
66
67
68
69
70
#!/usr/bin/env bash
#
# Worktemux: tmux session wrapper
# https://robots.thoughtbot.com/a-tmux-crash-course
#
# Alternatives:
# https://github.com/tmuxinator/tmuxinator
# https://github.com/tony/tmuxp
# https://github.com/tmux-plugins/tpm
# https://github.com/tmux-plugins/tmux-resurrect
# https://github.com/tmux-plugins/tmux-continuum
# https://superuser.com/questions/440015/restore-tmux-session-after-reboot

# Default options.
opts=""
name="$1"
state="$2"
socket="-L${name}"

# Session selection.
if [ ! -z "${name}" ]; then
  if [ "${name}" = "root" ]; then
    sudo tmux attach
    exit
  fi

  if ! tmux ${socket} list-sessions 2> /dev/null | grep -q "^${name}:"; then
    session="new-session -d -s ${name}"

    # Use a unique, per-session name
    #session="${session} -t ${name}"

    # Ensure there's a separate server running for each session.
    #
    # This achieves session isolation by using a unique socket per session.
    #
    # This solves tmux creating too many environment variables and triggering
    # the following error when using programs such as "less" and "ranger":
    #
    #   Error: too many environment variables: >= MAX_ENVS (256)
    #
    # For a list of tmux environment variables available within a session,
    # type "env | grep TMUX".
    #
    # Reference:
    # https://github.com/tmux/tmux/wiki/Advanced-Use
    session="${socket} ${session}"

    if [ -f "$HOME/.tmux/${name}" ]; then
      opts="$HOME/.tmux/${name}"
    elif [ -f "$HOME/.tmux/base" ]; then
      opts="$HOME/.tmux/base"
    else
      opts=""
    fi

    # Start session.
    if [ ! -z "${opts}" ]; then
      tmux ${session} \; source-file ${opts}
    else
      tmux ${session}
    fi
  fi

  if [ "$state" != "detached" ]; then
    tmux ${socket} attach -t ${name}
  fi
else
  tmux
fi