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

3

7

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.

Transit answered 6/11, 2013 at 19:1 Comment(2)
Try to use if condition in your .zsh file (under your root directory) and set prompt = '...'Pinup
If you have a function call in your prompt, ZSH will call that function every time the prompt is drawn. If you use an if... to set the prompt, your prompt will be set once (at loading) and won't change afterwards. I'd put a conditional in a function: see this question for an example.Recital
C
4

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

export PROMPT="%(%m==PROD.ifTrue.ifFalse)"
Caponize answered 23/5, 2021 at 7:7 Comment(0)
D
2

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.
Diuresis answered 6/11, 2013 at 20:29 Comment(0)
N
-3

Edit .zprofile file in your root Directory, with conditions applied on the specific user logged into.

Nebulize answered 6/11, 2013 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.