Marco Pracucci

Display the current kubectl context in the Bash prompt

by Marco Pracucci Comments

It’s an hot day at Spreaker: we’re finally rolling out to production the very first piece of our next-generation infrastructure, based upon Docker and Kubernetes. Now that we’ve two environments running Kubernetes (staging and prod) it’s vital we don’t mess up with kubectl, manually running on production commands that were supposed to run in our staging environment.

The easy way to reduce such risk that came out to my mind is to display the current kubectl context in the shell prompt. Basically, something like this:


After a quick Google search, I didn’t find anything similar (please correct me if I’m wrong), so here is how I did it.

1. Create ~/

Create a script in your home with the following content. It just defines a function __kube_ps1() that prints the current kubectl context (if any):


    # Get current context
    CONTEXT=$(cat ~/.kube/config | grep "current-context:" | sed "s/current-context: //")

    if [ -n "$CONTEXT" ]; then
        echo "(k8s: ${CONTEXT})"

## 2. Edit your Bash prompt in ~/.bash_profile

Edit the file .bash_profile in your home, loading ~/ and injecting __kube_ps1() in your prompt. For example, my prompt is:


source ~/

export PS1="${BLUE}\W ${GREEN}\u${YELLOW}\$(__kube_ps1)${NORMAL} \$ "

You may also be interested in ...

Upcoming conferences

I will join the following conferences. Reach me out on Twitter if you wanna meet:
Incontro DevOps 2020 Virtual 22 October 2020