Search code examples
zshpromptzshrc

How can I get the "rainbow prompt" in zsh?


I love the so-called "rainbow prompt" in bash:

enter image description here

which I produce thus:

export PS1="\[$(tput bold)\]\[$(tput setaf 1)\][\[$(tput setaf 3)\]\u\[$(tput setaf 2)\]@\[$(tput setaf 4)\]\h \[$(tput setaf 5)\]\W\[$(tput setaf 1)\]]\[$(tput setaf 7)\]\\$ \[$(tput sgr0)\]"

Unfortunately, that code doesn't work in zsh (which is my main shell).

How can I accomplish the same result in zsh?


Solution

  • It's much simpler in zsh, since the shell provides terminal-independent escape sequences for setting the color. For example:

    PS1='%B[%F{red}%n%F{green}@%F{blue}%m %F{purple}%~] %# %b%f'
    
    • %B/%b - turn bold on/off
    • %F{...} - set foreground color. You can use color names for the basic colors, or integer indices like %F{173} for terminals with larger palettes.
    • %f - turn off changes to foreground color (i.e., use default color)
    • %n - user name
    • %m - hostname up to first .
    • %~ - directory name
    • %# - # for root, % for normal user (If you still want $ instead of %, this is just a shortcut for the general conditional sequence %(!.#.%%), which you can replace with %(!.#.$), as seen in man zshmisc, under Shell state.)

    See man zshmisc, under "EXPANSION OF PROMPT SEQUENCES" for the full list.