Write a custom bash completion script for tmux attach

I have a script I use to attach to existing, or create a new, tmux session. ~/bin/tat looks like the following

# List existing tmux sessions, attach to existing, or create a new session
# stigok, feb 2019

if [ -z $1 ]; then
  tmux list-sessions
  tmux new -As $1

Then I wanted to be able to tab-complete existing session names, instead of first having to write tmux ls (or tat) to get list of open sessions. This led to /etc/bash_completion.d/tat:

# stigok, feb 2019
    local cur opts arglen

    # All existing tmux session names
    opts="$(tmux ls -F '#{session_name}')"

    # The `tat` binary should only accept a single argument.
    # Only trigger completion on the first arg (after the binary name itself)
    if [ $arglen -eq 2 ]; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
complete -F _tat tat

Works beautifully. Now I wonder how I should package this in order to keep the completion code closer to the shell script itself…


If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom)