Recursive ssh config files and bash hostname completion

I use ssh a lot, so hostname completion in bash is a must. Lately I’ve introduced Include┬ástatements in the ssh configuration files. Below the adapted bash completion code to handle this:

_ssh_completions () {
        local cur=${COMP_WORDS[COMP_CWORD]}
        local prev=${COMP_WORDS[COMP_CWORD-1]}

        COMPREPLY=( $(
                set -- $HOME/.ssh/config;
                while [ $# -gt 0 ]; do
                        f=$(eval echo $1)
                        shift
                        set -- $@ $(awk '/^Include /{print $2}' $f)
                        awk '/^Host [a-zA-Z0-9._ -]+$/ {sub("^Host ", ""); gsub(" ", "\n"); print $0;}' $f
                done | sort -u | grep "^$cur"
                ) )
}
complete -o default -o nospace -F _ssh_completions scp sftp ssh mosh rsync ssh-copy-id

Add it to your .bashrc and you should be good to go.

Leave a Reply

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