Skip to content

Instantly share code, notes, and snippets.

@jbrisbin
Created October 28, 2017 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrisbin/00bccb4af2a838298390cd1daa9820e0 to your computer and use it in GitHub Desktop.
Save jbrisbin/00bccb4af2a838298390cd1daa9820e0 to your computer and use it in GitHub Desktop.
BASH completion for kubectl
#!/bin/bash
KUBE_COMPLETE_COMMANDS=$(kubectl | egrep '^ ([a-z]*)' | awk '{print $1}')
_get_root_cmds() {
kubectl | egrep '^ ([a-z]*)' | awk '{print $1}'
}
_get_root_opts() {
echo $(kubectl options | egrep '\-[a-z][A-Z]*' | awk -F: '{print $1}' | awk -F= '{print $1}') | tr -d ,
}
_get_commands() {
kubectl $1 2>&1 | awk '/Available Commands:/{f=1;next} /Options:/{f=0} f' | awk '{print $1}'
}
_get_options() {
echo $(_get_root_opts) `echo $(kubectl $1 -h 2>&1 | awk '/Options:/{f=1;next} /Usage:/{f=0} f' | awk -F: '{print $1}' | awk -F= '{print $1}') | tr -d ,`
}
_get_get_subcommands() {
kubectl get 2>&1 | egrep '^ \* ([a-z]*)' | awk '{print $2}'
}
_get_explain_subcommands() {
kubectl explain 2>&1 | egrep '^ \* ([a-z]*)' | awk '{print $2}'
}
_get_from_table() {
kubectl $1 $2 2>/dev/null | tail -n+2 | awk '{print $1}'
}
_kubectl()
{
local cur=${COMP_WORDS[COMP_CWORD]}
local prev=${COMP_WORDS[COMP_CWORD-1]}
local words_sugg=""
if [[ "$prev" == create ]]; then
if [[ "$cur" == -* ]]; then
case "$cur" in
-n)
words_sugg=$(_get_from_table "get" "namespaces")
;;
--namespace)
words_sugg=$(_get_from_table "get" "namespaces")
;;
*)
words_sugg=$(_get_options "create")
;;
esac
else
words_sugg=$(_get_commands "create")
fi
elif [[ "$prev" == get ]]; then
local subc=$(_get_get_subcommands)
if [[ "$cur" == -* ]]; then
words_sugg=$(_get_options "get")
elif [[ -z "$cur" || "${subc[@]}" =~ $cur ]]; then
words_sugg=$subc
else
words_sugg=$(_get_from_table $prev $cur)
fi
elif [[ "$prev" == explain ]]; then
if [[ "$cur" == -* ]]; then
words_sugg=$(_get_options "explain")
else
words_sugg=$(_get_explain_subcommands)
fi
elif [[ "$prev" != -* && -z "$cur" || "${KUBE_COMPLETE_COMMANDS[@]}" =~ $cur ]]; then
if [[ "$prev" == "kubectl" && "$cur" == -* ]]; then
words_sugg=$(_get_root_opts)
elif [[ "$prev" == deployments ]]; then
local prev2=${COMP_WORDS[COMP_CWORD-2]}
words_sugg="$(_get_from_table $prev2 $prev)"
elif [[ "$prev" == "kubectl" ]]; then
words_sugg="$(_get_root_cmds)"
else
return 0
fi
elif [[ "$cur" == -* ]]; then
local prev2=${COMP_WORDS[COMP_CWORD-2]}
words_sugg=$(_get_options $prev2)
elif [[ "$prev" == -* ]]; then
case "$prev" in
-n)
words_sugg=$(_get_from_table "get" "namespaces")
;;
--namespace)
words_sugg=$(_get_from_table "get" "namespaces")
;;
*)
local prev2=${COMP_WORDS[COMP_CWORD-2]}
words_sugg=$(_get_options $prev2)
;;
esac
else
return 0
fi
COMPREPLY=( $(compgen -W "$words_sugg" -- $cur) )
}
complete -F _kubectl kubectl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment