Web development and useful information

Nathan's Blog

tmux – ‘attach session’ alias with tab completion

The command to reattach a tmux session is tedious to type.
If you have many sessions open, or don’t remember the session name, you might type:

# List sessions
tmux ls
logs: 2 windows (created Thu Mar 13 13:07:19 2014) [237x62]
turtle: 1 windows (created Tue Mar 18 13:57:21 2014) [237x65]

# Attach to the session named turtle
tmux attach -t turtle

Create the alias

Lets create an alias to make attaching to tmux sessions easier.
The alias will allow us to autocomplete tmux session names, avoiding tmux ls.

1. Bash completion

create a new file using your preferred editor:

vim /etc/bash_completion.d/tma

Paste the following.

_tma() {
    TMUX_SESSIONS=$(tmux ls -F '#S' | xargs)

    local cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=( $(compgen -W "$TMUX_SESSIONS" -- $cur) )
}
complete -F _tma tma

Save and quit.

2. Bash alias

Add the following to your ~/.bashrc

alias tma='tmux attach -t $1'
if [ -f /etc/bash_completion.d/tma ]; then
. /etc/bash_completion.d/tma
fi

Source your ~/.bashrc to pickup the bash_completion.

source ~/.bashrc

3. Use tma

tma turt[Tab]

If a session named turtle exists, it will complete to: tma turtle
Press enter and it will attach your tmux session.

If you have one session open, pressing tab will autocomplete it.

Previous

Passing the Life in the UK Test

Next

Easy DNS switching on OS X

6 Comments

  1. Anonymous

    TMUX_SESSIONS=$(tmux ls -F '#S' | xargs)

  2. meneelyt

    Thanks – exactly what I was looking for.

  3. Tri

    Any way to do this without creating a new bash alias? That is, tab autocomplete on the -t flag?

  4. Thanks! I massaged it a little bit into the snippet below for my .bashrc:

    if [ -x “$(command -v tmux)” ] && [ ! -x “$(command -v tmax)” ]; then
    tmax() {
    if ((${#1} > 0)); then
    tmux attach -t “$1” || tmux new -s “$1”
    else
    tmux attach || tmux new
    fi
    }
    _tmax() {
    read -ra COMPREPLY <<< "$(compgen -W "$(tmux ls -F '#S' | xargs)" — \
    "${COMP_WORDS[COMP_CWORD]}")"
    }
    complete -F _tmax tmax
    fi
    [ ! -x "$(command -v tmls)" ] && alias tmls='tmux ls'

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress & Theme by Anders Norén