How to get the current namespace of current context using kubectl

I am trying to get the namespace of the currently used Kubernetes context using kubectl.

I know there is a command kubectl config get-contexts but I see that it cannot output in json/yaml. The only script I've come with is this:

kubectl config get-contexts --no-headers | grep '*' | grep -Eo '\S+$'

This works fine if you have a namespace selected in your context

kubectl config view --minify --output 'jsonpath={..namespace}'; echo

You can always show up your current context and namespace in your prompt with kube-ps1


Easy to memorize command line

kubectl config view | grep namespace

This will print the current namespace being used.

$kubectl config view --minify | grep namespace