10

I'm trying to use ANSI escape sequences to set the color of my zsh prompt, but the escape character (\e) seems to be being escaped when displaying the prompt. Here's an example of what I'm running and the output I'm getting:

> autoload promptinit && promptinit
> autoload colors && colors
> echo "Not sure if those two lines are required" > /dev/null
> PROMPT="\e[32mhi> "
\e[32mhi> echo "Note that the escape character wasn't interpreted correctly" > /dev/null
\e[32mhi> print -P "$PROMPT"
hi>
\e[32mhi> echo "The hi> was printed in green, as I want" > /dev/null

The zsh print documentation seems to say the -P flag makes it print as if it was in the prompt, but it doesn't match the actual prompt behavior. Does anyone know why the escape character doesn't work?

I tried using $fg_no_bold, and things like $fg_no_bold[red] do work, but I'd like to use more than the 8 standard colors, but $fg_no_bold[32] doesn't work (for any number, not just 32). If getting 256 colors working with $fg_no_bold is easier, then I'd be ok doing that!

Thanks!

AlexB
  • 6,664
  • 12
  • 46
  • 66
robbiemc
  • 103
  • 1
  • 5

2 Answers2

16

You need to use dollar single quote in order to tell zsh to interpret ANSI escape sequences. So

PROMPT=$'\e[32mhi> '

will do what you want, however it is safer to additionally put all special codes inside %{...%} brackets to treat code literally and prevent unwanted moving of the cursor position. Moreover you should change back the colour to the default, unless you want to colourize all terminal text foreground to green.

After all your prompt setting should look like

PROMPT=$'%{\e[32m%}hi> %{\e[0m%}'
jimmij
  • 321
  • 6
  • 12
15

zsh provides built-in support for changing the color without having to deal with ANSI escape codes directly.

PROMPT="%F{green}hi>%f "
chepner
  • 389,128
  • 51
  • 403
  • 529
  • 1
    The One True Answer emerges from the murky bowels of `"man zshmisc"`. – Cecil Curry Nov 01 '18 at 05:10
  • This works with the terminal database, so also works with terminals that do not use ANSI escape sequences. (A pleasant surprise!) Portable and arguably more legible. Also supports terminals that support 256-color and 16-million color. `man zshzle` – Eljay Mar 15 '21 at 14:50