Bash Completion

 

为特定命令编写 Bash 下的自动补全函数。

SSH 服务器名称自动补全

$ mkdir -p /etc/bash_completion.d

# ssh 的自动补全代码 
$ vim /etc/bash_completion.d/ssh
_ssh()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=$(grep '^Host' ~/.ssh/config ~/.ssh/config.d/* 2>/dev/null | grep -v '[?*]' | cut -d ' ' -f 2-)

    COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
    return 0
}
complete -F _ssh ssh

$ echo "source /etc/bash_completion.d/ssh" >> ~/.bashrc

$ source ~/.bashrc

参考链接