简体   繁体   中英

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

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.

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* , ie, 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.

编辑根目录中的.zprofile文件,并在登录的特定用户上应用条件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM