Skip to content

Tmux

Tmux는 사용자가 단일 단말기 창 또는 원격 터미널 세션 안에서 여러 별도의 터미널 세션에 엑세스 할 수 있도록 여러 가상 콘솔을 다중화하는데 사용할 수 있는 소프트웨어 애플리케이션이다. 이 애플리케이션은 명령어 인터페이스로 부터 다수의 프로그램을 처리하고 유닉스 셸부터의 프로그램을 분리하는데에 유용하다. 이것은 GNU Screen과 동일한 기능을 많이 제공하지만 BSD 허가서로 배포됩니다.

Categories

Plugins

ETC

Keymaps

아래 명령은 모두 prefix 이후 입력. prefix 기본 값은 <CTRL-B> 이다.

명령 앞에 :는 프롬프트로 이동한다.

Windows (tabs)

  • c - new window
  • , - name window
  • w - list windows
  • f - find window
  • & - window 종료
  • . - move window - prompted for a new number
  • :movew<CR> - move window to the next unused number
  • {화살표} - 창 이동
  • c - 창 세트 하나 더 만들기
  • {0~9} - 창 이동 (하단에 번호 확인)

Panes (splits)

  • % - 창 열로 분할
  • " - 창 행로 분할
  • o - swap panes
  • q - show pane numbers
  • x - pane 종료
  • Alt+2 - 사이즈 동일하기 해주기 (열로 동일하게)
  • Alt+1 - 사이즈 동일하기 해주기 (행으로 동일하게)
  • {space} - Toggle between layouts
  • <Ctrl-o> - pane 순서 변경 (시계 반대)
  • <Alt-o> - pane 순서 변경 (시계 방향)

ETC

  • z: Toggle Fullscreen
  • d - Detach
  • t - 현재 시간 대문짝만하게 보여주기

명령들

  • tmux new-session -s SESSION_NAME - 세션명으로 새로 할당
    • tmux new -s SESSION_NAME 동일
  • tmux list-sessions - 현재 열려있는 세션 목록을 보여준다.
    • tmux ls 동일
  • tmux attach-session -t TARGET_SESSION - TARGET_SESSION이라는 이름의 세션으로 들어간다.
    • tmux a -t SESSION_NAME 동일
  • tmux kill-session -t SESSION_NAME - SESSION_NAME 제거
  • tmux has-session -t TARGET_SESSION - TARGET_SESSION이라는 이름의 세션이 열려있는지 확인해본다.

설정 파일 지정 방법

  • /etc/tmux.conf - 시스템 전역 설정 파일 위치 (모든 사용자에게 적용)
  • ~/.tmux.conf - 사용자 전용 설정 파일 위치
  • TMUX_CONF=~/custom/tmux.conf - 환경 변수 사용.
  • tmux -f /path/to/custom-tmux.conf - 명령행 지정 사용.

환경 변수

TMUX
tmux 세션이 실행 중일 때 설정되는 변수입니다.
현재 tmux 세션의 소켓 경로 및 PID를 포함하며, tmux 내부에서 실행될 때 설정됩니다.
세션 외부에서의 직접적인 설정은 일반적이지 않습니다.
TMUX_CONF
tmux 설정 파일 경로를 사용자 정의할 때 사용됩니다.
특정 설정 파일을 사용하고자 할 때 이 변수를 설정하여 tmux 실행 시 지정한 파일을 불러오도록 할 수 있습니다.
기본 설정: export TMUX_CONF=/path/to/your/tmux.conf
TMUX_PLUGIN_MANAGER_PATH
tpm (tmux plugin manager)을 사용할 때 플러그인 설치 위치를 지정하는 변수입니다.
기본 경로: ~/.tmux/plugins (별도로 설정하지 않으면 기본값이 사용됩니다)
TMUX_TMPDIR
tmux가 임시 파일을 저장하는 디렉토리를 설정하는 변수입니다.
시스템의 기본 /tmp 대신 다른 임시 디렉토리를 지정하고자 할 때 유용합니다.
TERM
터미널 에뮬레이션을 지정하며, tmux에서 중요한 변수입니다. 일반적으로 xterm-256color 또는 screen-256color로 설정되어야 합니다.
설정 예시: export TERM=xterm-256color
PATH
tmux가 실행될 때 PATH 환경 변수가 올바르게 설정되어 있어야 tmux가 필요한 외부 프로그램을 찾을 수 있습니다.
특히 root와 일반 사용자 간에 이 경로가 다를 수 있어, 경로에 tmux가 올바르게 포함되어 있는지 확인하는 것이 좋습니다.
LC_CTYPE, LC_ALL, LANG
tmux에서 UTF-8 등의 문자 인코딩을 지원하기 위한 로케일 설정 변수입니다.
올바른 로케일 설정(en_US.UTF-8 등)을 지정해야 tmux에서 특수 문자나 유니코드가 정상적으로 표시됩니다.

로그 파일

tmux는 기본적으로 로그 파일을 자동으로 생성하지 않기 때문에, 로그를 저장하려면 다음 명령으로 세션을 시작하여 로그를 남길 수 있습니다.

tmux new-session -f ~/.tmux.conf 2> ~/tmux.log

tmux 세션 내에서 특정 명령 출력을 파일에 기록하려면 다음 명령을 사용할 수 있습니다:

tmux pipe-pane -o 'cat > ~/tmux_output.log'

tmux 서버 로그 확인:

tmux -vvvv new-session

tmux-server-*.log 형식의 파일을 /tmp 위치에 생성합니다.

.tmux.conf 파일에 로그 설정을 추가해 로그를 활성화할 수도 있습니다.

set-option -g status on
set-option -g message-command-style bg=yellow,fg=black
set-option -g terminal-overrides 'xterm*:smcup@:rmcup@'

이렇게 설정한 후 tmux를 재시작하여 로그와 명령 스타일을 확인하면 좀 더 오류를 쉽게 추적할 수 있습니다.

이 방법들을 사용하여 tmux 세션 및 설정 관련 로그를 기록하고 문제 해결에 사용할 수 있습니다.

Truecolor

터미널 설정은 Terminal emulator#Truecolor항목 참조.

# 256 color mode.
set -g default-terminal "screen-256color"

# TrueColor/RGB capability set
set -sa terminal-overrides ",xterm-256color:RGB"

Reloading tmux config

If you have made changes to your tmux configuration file in the ~/.tmux.conf file, it shouldn’t be necessary to start the server up again from scratch with kill-server. Instead, you can prompt the current tmux session to reload the configuration with the source-file command.

This can be done either from within tmux, by pressing Ctrl+B and then : to bring up a command prompt, and typing:

:source-file ~/.tmux.conf

Or simply from a shell:

$ tmux source-file ~/.tmux.conf

This should apply your changes to the running tmux server without affecting the sessions or windows within them.

Change prefix key

C-s로 변경하고 싶다면 ~/.tmux.conf파일에 아래 내용을 추가한다.

set -g prefix C-s
unbind C-b

# 현재, 터미널에 실행중인 프로그램에 prefix 키를 전송한다.
bind C-s send-prefix

Session

# 새로운 Session 만들기 - session 이름은 설정하지 않고 (0,1,2,.. 순서로 생성)
tmux

# 새로운 Session 만들기 - session 이름 = (session_name)
tmux new -s (session_name)

# Session name 수정
ctrl + b, $
# 원하는 이름 적고 Enter

# Session 종료 - session 사라짐
exit or ctrl + d # 주의! window나 pane이 열려있을 때는 pane -> window 순으로 하나씩 닫힘

# Session 닫기(detach) - 백그라운드에서 계속 돌아감(server 접속이 끊겨도 계속 돌아감)
# 매우 유용하게 사용할 수 있습니다 - tmux의 엄청 큰 장점
ctrl + b, d

# Session 목록 확인
tmux ls

# Detached session 다시 열기(attach)
tmux at -t (session_name)
# (session_name)은 tmux ls로 확인

Tmux open new pane in same directory

새로운 윈도우를 열 때 현재 디렉토리 위치를 유지하고 싶다면 -c "#{pane_current_path}"를 사용하면 된다:

# Set the control character to Ctrl+Spacebar (instead of Ctrl+B)
set -g prefix C-space
unbind-key C-b
bind-key C-space send-prefix

# Set new panes to open in current directory
bind c new-window -c "#{pane_current_path}"
bind '"' split-window -c "#{pane_current_path}"
bind % split-window -h -c "#{pane_current_path}"

Mouse mode

## 2.1 이상 버전
set -g mouse on

## 2.1 아래 버전
set -g mode-mouse on

## UTF-8 문자열 선택 여부 (최신버전에서 작동하지 않는듯?)
set -g mouse-utf8 on

만약 iTerm2을 사용한다면 아래 설정을 Enable 해야 한다.

Profiles -> Terminal -> Save lines to scrollback when an app status bar is present

환경변수 설정

config 파일에서

set-environment -g MY_VARIABLE value

메시지 출력

tmux display-message [-aINpv] [-c target-client] [-d delay] [-F format] [-t target-pane] [message]

자주 사용되는 포맷 문자열

  • #S - 세션 이름
  • #I - 창 번호
  • #P - 패널 번호
  • #W - 창 이름
  • #T - PC 이름
  • #{window_width} - 창의 너비
  • #{window_height} - 창의 높이

System Clipboard

tmux logging

$ tmux capture-pane -pS -1000000 > tmux.log

Clear history

$ tmux clear-history

Session

Starting a Tmux Session:

tmux new-session -s <session-name>

Connecting to existing session:

tmux attach -t <session-name>

neovim 호환

  - OK: escape-time: 0ms
  - INFO: $TERM: screen
  - ERROR: $TERM should be "screen-256color" or "tmux-256color" in tmux. Colors might look wrong.
    - ADVICE:
      - Set default-terminal in ~/.tmux.conf:
          set-option -g default-terminal "screen-256color"
      - https://github.com/neovim/neovim/wiki/FAQ
  - WARNING: Neither Tc nor RGB capability set. True colors are disabled. |'termguicolors'| won't work properly.
    - ADVICE:
      - Put this in your ~/.tmux.conf and replace XXX by your $TERM outside of tmux:
          set-option -sa terminal-overrides ',XXX:RGB'
      - For older tmux versions use this instead:
          set-option -ga terminal-overrides ',XXX:Tc'

로그(히스토리) 저장

bind-key P command-prompt -p 'save history to filename:' -I '~/tmux.history' 'capture-pane -S -32768 ; save-buffer %1 ; delete-buffer'

-> 아직 테스트 못해봤다. 나중에 해보자.

set vs set-option

똑같다. 그냥 set-option의 별칭이 set이다.

tmux-session

단순하게, bash 스크립트로 처리하는 방법:

#!/usr/bin/env bash
# Save and restore the state of tmux sessions and windows.
# TODO: persist and restore the state & position of panes.
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

대안으로, tmux-resurrect 를 설치하는것도 추천.

Troubleshooting

libevent 충돌 문제

dyld: Library not loaded: /usr/local/lib/libevent-2.0.5.dylib

libevent를 제거하고 다시 설치해보자.

$ brew uninstall libevent
$ brew install tmux

ESC 반응 속도 문제

vim과 함계 사용할 때 등, ESC 반응속도가 느리다면 ~/.tmux.conf파일에 아래의 내용을 추가하자.

set -sg escape-time 0

설정파일 수정사항이 반영되지 않는 문제

만약 tmux 서버 세션이 켜져있을 경우 정상적으로 반영되지 않는다. 서버를 종료하고 다시 시작해야 한다.

$ tmux kill-server

See also

Favorite site

Configurations