Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format my zsh prompt based on a condition? [closed]

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.

like image 547
Bonz0 Avatar asked Nov 06 '13 19:11

Bonz0


People also ask

How do I customize zsh prompt on Mac?

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.

How do you make a custom zsh prompt?

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.

What is PROMPT_SUBST?

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 `!


2 Answers

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.
  • Check if it matches the pattern *PROD*, i.e., does the host name contain PROD.
  • Take whatever the value of 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.
  • Add 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.
like image 95
chepner Avatar answered Dec 16 '22 01:12

chepner


Its easy to do now you can use the conditional substring
This is the syntax %(condition.ifTrue.ifFalse)

export PROMPT="%(%m==PROD.ifTrue.ifFalse)"
like image 41
Unnat Avatar answered Dec 16 '22 00:12

Unnat