Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically add environment variables to zsh prompt?

Tags:

shell

zsh

EDIT: Original title said "bash prompt", but I use "zsh". I accepted @Artur R. Czechowski's answer because it was correct in a bash context and I was able to make mine work with his help. PROMPT is now ' ${ENV}${ENV:+ } %F{249}${PWD/#$HOME/~} %{$fg[green]%}'○' ', just adding the bit about ENV was all I needed.

ORIGINAL POST: As part of my job, I change environment variables frequently. So frequently that I feel I'm going to inevitably going to forget which one I'm in and do something I shouldn't. In case it's relevant to you answering my question, I change environment by running a shell script and my current bash prompt is PROMPT=' %F{249}${PWD/#$HOME/~} %{$fg[green]%}'○' '.

If I'm in a virtual environment, such as venv, then my prompt gets prefaced with (.venv). How do I get something similar with an environment variable such as DB_HOST or whatever variable I want? If DB_HOST changes, I want the bash prompt to change right away and persist.

like image 200
Jason Avatar asked Sep 19 '25 20:09

Jason


1 Answers

PROMPT_COMMAND is your answer. Example:

myprompt() {
    PS1="${DB_HOST}${DB_HOST:+ }\u@\h:\w\$ "
}

PROMPT_COMMAND=myprompt

It will always display current value of DB_HOST variable.

like image 161
ArturFH Avatar answered Sep 21 '25 17:09

ArturFH