Skip to content

Instantly share code, notes, and snippets.

@dale-c-anderson
Last active March 21, 2025 17:25
Show Gist options
  • Save dale-c-anderson/0fc557840171468420cc9ad656a16032 to your computer and use it in GitHub Desktop.
Save dale-c-anderson/0fc557840171468420cc9ad656a16032 to your computer and use it in GitHub Desktop.
Kubectl Context switcher
#!/bin/bash
# Usage: kc [<partialmatch>]
# Where <partialmatch> can be any case insensitive string that partially matches one of your contexts. (not a regexp)
# If there's only one match, context will be switched.
# If there's more than one match, it'll list them so you can try again and be more specific.
# If there's no matches, context is not switched. Run it again without a pattern to see your contexts.
# If you don't supply a pattern, it just lists all your contexts.
# shellcheck disable=SC2034
BOLD=$(tput bold 2>/dev/null) || BOLD='\033[1;33m' # orange, if tput isnt available.
# shellcheck disable=SC2034
UNBOLD=$(tput sgr0 2>/dev/null) || UNBOLD='\033[m'
function local_cerr () {
>&2 echo "$*"
}
function local_err () {
local_cerr "❌ ${BOLD}ERR${UNBOLD}: $*"
}
function local_warn () {
local_cerr "⚠️ ${BOLD}WARN${UNBOLD}: $*"
}
function red_x () {
>&2 echo "❌"
}
function green_check () {
>&2 echo "✅"
}
# kubectl context switcher
function kc () {
command -v kubectl > /dev/null || {
local_err "Install kubectl and try again."
return 1;
}
local TARGET_CONTEXT
TARGET_CONTEXT=${1:-}
local CONTEXTS
CONTEXTS=$(command kubectl config get-contexts --no-headers=true -o=name)
CURRENT_CONTEXT=$(command kubectl config current-context)
if [ -z "$TARGET_CONTEXT" ]; then
>&2 echo "${BOLD}Choose a new context to switch to:${UNBOLD}"
local HIGHLIGHTED
HIGHLIGHTED=$(echo "$CONTEXTS" | grep --color=always -E "^|$CURRENT_CONTEXT")
>&2 echo "$HIGHLIGHTED"
return 0
fi
local FILTERED
FILTERED=$(echo "$CONTEXTS" | grep -i "$TARGET_CONTEXT")
if [ -z "$FILTERED" ]; then
local_err "No context matches '$TARGET_CONTEXT'"
return 1
fi
NUM_RESULTS=$(echo "$FILTERED" | wc -l)
if [[ "$NUM_RESULTS" == "1" ]]; then
(set -x && command kubectl config use-context "$FILTERED")
green_check
return 0
else
local_err "Too many results:"
local_cerr "$FILTERED"
return 1
fi
}
kc "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment