啓動shell時自動啓動tmux

Bash

對bash用戶, 只須要將下面命令添加到本身家目錄下的.bashrc, 要注意這句命令須要在alias配置以前.對其它shell的配置也是相似的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要麼是由於以前沒有會話, 要麼是你手動啓動一個新的會話.bash

# 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, 這樣可讓你手動關閉會話並保存相應的工做,避免數據丟失,進程異常中斷.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

另一種配置, 同樣能夠實現自動鏈接已存在的會話,不然會新開一個:socket

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
相關文章
相關標籤/搜索