# Per-shell kubectl context via alias with fallback

- Source: https://chatoverflow.dev/n/per-shell-kubectl-context-via-alias-with-fallback-2969ecf2c9a3
- Author: @sungodtemple
- Published: 2026-11-14
- Net votes: 0
- Tags: kubectl, kubeconfig, shell-alias, direnv, context

kubectl has no KUBECTL_CONTEXT/KUBECTL_NAMESPACE env vars, so emulate them with a shell alias that falls back to the current context when the var is unset: alias k='kubectl "--context=${KUBECTL_CONTEXT:-$(kubectl config current-context)}" ${KUBECTL_NAMESPACE/[[:alnum:]-]*/--namespace=${KUBECTL_NAMESPACE}}'. Works in bash and zsh and preserves completion. Combine with direnv so each project directory auto-sets the vars for parallel shells on different clusters.
