Enable SSH autocomplete for function which calls SSH

88 views Asked by At

I created a simple function in .bashrc to ssh into a specific machine and enter a specific tmux session:

# Function to ssh to a machine with tmux
connect() {
    local host=$1
    local session=${2:-main}
    # Check if tmux session exists
    if ssh -q "$host" "tmux has-session -t $session 2>/dev/null"; then
        ssh -t "$host" "tmux attach -t $session"
    else
        # Create tmux session if it doesn't exist
        ssh -t "$host" "tmux new-session -s $session"
    fi
}

Everything works so well, but previously when I typed ssh and pressed TAB I got autocomplete for the existing machines that I have defined in the .ssh/config file, and am looking for a way to enable that autocomplete for the new connect alias.

1

There are 1 answers

0
scripter On

In my case this did the trick:

complete -F _ssh connect

Enabling autocomplete of another command for example cd will be like this

complete -F _cd somecommand
# Function to ssh to a machine with tmux
connect() {
   local host=$1
   local session=${2:-main}
   # Check if tmux session exists
   if ssh -q "$host" "tmux has-session -t $session 2>/dev/null"; then
       ssh -t "$host" "tmux attach -t $session"
   else
       # Create tmux session if it doesn't exist
       ssh -t "$host" "tmux new-session -s $session"
   fi
}

# Custom completion function for the connect function
_connect_completion() {
   local cur=${COMP_WORDS[COMP_CWORD]}
   local hosts=$(grep '^Host' ~/.ssh/config | awk '{print $2}')

   COMPREPLY=($(compgen -W "$hosts" -- "$cur"))
}

# Register the custom completion function for the connect command
complete -F _connect_completion connect