I'm using the answer given here: How do zsh ansi colour codes work? to format and add color to my zsh prompt.
Is there any way to format the prompt based on some conditions?
For example, if the hostname has the word PROD
in it, then I'd like my prompt to have a red background. Otherwise, I'd like no background, and bold green text.
To make any change to the default zsh prompt, you'll have to add relevant values for the prompt to appear differently than the default. It'll be blank if you're accessing it for the first time. You can add a new line with the text PROMPT='...' and include relevant values in the ellipses.
To customize the ZSH prompt, we need to modify the prompt= variable inside the . zshrc file. We can populate the prompt variable with various placeholders, which will alter how the ZSH prompt appears.
If the PROMPT_SUBST option is set, the prompt string is first subjected to parameter expansion, command substitution and arithmetic expansion. See section Expansion. Certain escape sequences may be recognised in the prompt string. If the PROMPT_BANG option is set, a `!
You can set a precmd
function that resets your prompt just before it is displayed each time.
set_red_prompt_background () {
if [[ ${(%):-%M} = *PROD* ]]; then
PS1="%K{red}$PS1%k"
else
PS1="%F{green}%B$PS1%f%b"
fi
}
typeset -a precmd_functions
precmd_functions+=(set_red_prompt_background)
This isn't tested, so I'd be surprised if it works as is. But here's how it's intended to work.
${:-foo}
is a special type of "parameter" expansion which just expands to the word following the :-
. Seems useless at first...${(%):-%M}
is the same as above, but has the (%)
flag to instruct zsh
to process any prompt escapes found in the expansion. This turns into a fancy way of getting the full host name that would appear in the prompt using the %M
escape.*PROD*
, i.e., does the host name contain PROD.PS1
is, and wrap it in %K{red}...%k
to make the background red. Note that this might override any background colors already set in PS1
.set_red_prompt_background
to the list of functions executed prior to displaying the prompt. If you add any functions after this, they could potentially override the color you set here. Its easy to do now you can use the conditional substring
This is the syntax %(condition.ifTrue.ifFalse)
export PROMPT="%(%m==PROD.ifTrue.ifFalse)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With