1. 程式人生 > >啟動shell時自動啟動tmux

啟動shell時自動啟動tmux

Bash

對bash使用者, 只需要將下面命令新增到自己家目錄下的.bashrc, 要注意這句命令需要在alias配置之前.對其它shell的配置也是類似的

~/.bashrc
# If not running interactively, do not do anything
[[ $- != *i* ]] && return
[[ -z "$TMUX" ]] && exec tmux
注意: 這些程式碼確保tmux不會在tmux中啟動(tmux巢狀於tmux中). tmux 通過設定環境變數$TMUX 來設定tmux啟動所用的socket, 如果$TMUX不存在,或者長度為0那麼就可以知道當前沒有執行tmux.

下面的配置會嘗試只啟動一個會話, 當你登入時, 如果之前啟動過會話, 那麼它會直接attach, 而不是新開一個. 想要新開一個session要麼是因為之前沒有會話, 要麼是你手動啟動一個新的會話.

# TMUX
if which tmux >/dev/null 2>&1; then
    #if not inside a tmux session, and if no session is started, start a new session
    test -z "$TMUX" && (tmux attach || tmux new-session)
fi

下面的配置實現的功能相似, 但是他會在啟動tmux之前先檢查一下tmux是否已經安裝. 它也會在你登出之前幫你重新連線上未關閉的session, 這樣可以讓你手動關閉會話並儲存相應的工作,避免資料丟失,程序異常中斷.

# TMUX
if which tmux >/dev/null 2>&1; then
    # if no session is started, start a new session
    test -z ${TMUX} && tmux

    # when quitting tmux, try to attach
    while test -z ${TMUX}; do
        tmux attach || break
    done
fi

另外一種配置, 一樣可以實現自動連線已存在的會話,否則會新開一個:

if [[ -z "$TMUX" ]] ;then
    ID="`tmux ls | grep -vm1 attached | cut -d: -f1`" # get the id of a deattached session
    if [[ -z "$ID" ]] ;then # if not available create a new one
        tmux new-session
    else
        tmux attach-session -t "$ID" # if available attach to it
    fi
fi