Include environment variables dynamically in your ZSH prompt

Rees Pozzi
2 min readMar 15, 2022

Sometimes it’s useful to have an environment variable listed within your prompt readout, you may be connecting to multiple DBs during a day, switching between K8S clusters, repositories, branches, the list goes on.

You may be inclined to take an approach like this in your ~/.zshrc file:

export var=$(zsh command)
PS1="%n ${var} %~"

The problem with the above is that export only runs on the creation / restart of the ZSH. This means that initially your prompt readout will be correct, but the export line is only ever run once for that session. I’ll show an example below with switching between K8S clusters and showing your current context in the prompt.

export currentContext=$(kubectl config current-context)
PS1="%F{208}% [rees] %F{155}[%W]%F{196} [${currentContext}]%F{152} %B%~ %F{255}%b"

When you restart the shell using the above in your ~/.zshrc file, you will have the current context listed correctly:

However, if you change the context by running kubectl config use-context “Cluster 2" , your prompt will remain as shown above, with the wrong context showing.

To fix this, you can use Hooks. There are multiple different kinds of hooks you can read about in more detail here, but in this case we’re just interested in precmd as this is executed before the prompt is displayed. So how does this work in practice?

#K8S 
#allows parameter…

--

--