Skip to content

Instantly share code, notes, and snippets.

@stigok
Last active December 30, 2022 11:30
Show Gist options
  • Save stigok/575ec818364fe1228749ce1e5d6a9667 to your computer and use it in GitHub Desktop.
Save stigok/575ec818364fe1228749ce1e5d6a9667 to your computer and use it in GitHub Desktop.
Cheap tmux session manager

Usage

Open a new session, named after the current working directory

$ tat -n

Attach to a named session, or create it if it does not exist

$ tat my-new-session

List existing session names

$ tat

Install

Put the script in a directory in your $PATH. Add completion script if you want bash completion.

Completion

$ mkdir -p ~/.local/share/bash-completion/completions/
$ cat <<'EOF' > ~/.local/share/bash-completion/completions/tat
# stigok, feb 2019
_tat()
{
    local cur opts arglen cwdname
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    arglen=${#COMP_WORDS[@]}
    cwdname=$(basename $(pwd))

    # All existing tmux session names
    opts="$(tmux ls -F '#{session_name}' 2> /dev/null)"

    # If no tmux session is active, complete with current dir name
    if [[ $? -ne 0 && $arglen -eq 2 ]]; then
        COMPREPLY=( $(compgen -W "$cwdname") )
        >&2 echo -e "No sessions. Completing with current dir name"
        return 0
    fi

    # 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
    fi
}
complete -F _tat tat
EOF
#!/bin/sh
# List existing tmux sessions, attach to existing, or create a new session
# stigok, feb 2019
if [ -z $1 ]; then
# List names of all existing tmux sessions
tmux list-sessions -F '#{session_name}'
elif [ $1 = '-n' ]; then
# Create a new session with name of the current working directory.
# Replace all punctuations with underscore, and remove question marks.
tmux new -As $(basename $PWD | tr '[:punct:]' - | tr -d '?')
else
# Create a new session with specified name
tmux new -As $(echo $1 | tr -d '?')
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment