I believe this is what they call “prompt engineering”.

username@hostname:~/pwd rm / rm: cannot remove '/': Is a directory username@hostname:~/pwd ^C username@hostname:~/pwd

I set the color of the colon : to the 8-bit color corresponding to the Exit status of the last executed command ($?). 0 is success, which maps to black, which is usually the background color, which makes it invisible until copied and pasted somewhere else. Any other value (1-255) makes it visible.

Everything else is pretty basic.

bash

PS1='\[\e[1;32m\]\u@\h\[\e[38;5;$?m\]:\[\e[34m\]\w\[\e[0m\] '

You might see \033 for octal character 33 instead of \e for escape. Hexadecimal \x1b and decimal \27 didn’t work.

The outer enclosing square brackets \[\] around each escape sequence may appear to be optional at first, but after testing, I found that omitting them causes weird behavior.

zsh

PS1='%B%F{green}%n@%m%b%F{%?}:%B%F{blue}%~%f%b '
bash1zsh2
Start boldface mode
Set foreground color green
\e[1;32m
Start boldface mode%B
Set foreground color green%F{green}
username of the current user\u%nusername
literal @ character@@@
hostname up to the first ’.‘.\h%mhostname
stop boldface mode%b
Set foreground color $?\e[38;5;$?m%F{%?}
literal : character:::
Set foreground color blue\e[34m%F{blue}
$PWD with $HOME replaced by a ’~‘.\w%~~/pwd
All attributes become turned off\e[0m
stop using a different foreground color%f
stop boldface mode%b
literal space character

Footnotes

  1. https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Controlling-the-Prompt

  2. man zshmisc