Do you ever feel like you’re going blind because the prompt text color and the result text color are the same? Here’s how to colorize your shell prompt.
Open your favorite text editor (vim or nano), edit your ~/.bashrc, and add this at the end:
1 2 3 | nano ~/.bashrc # add this line: PS1='\[\e[1;32m\][\u@\h \t \w]\$\[\e[0m\] ' |
The full set of color codes (the leading digit is the intensity: 0; for normal, 1; for bold/bright — so you have 16 colors, not 8):
1 2 3 4 5 6 7 8 | 0;30 black 1;30 dark gray 0;31 red 1;31 light red 0;32 green 1;32 light green 0;33 brown/yellow 1;33 yellow 0;34 blue 1;34 light blue 0;35 purple 1;35 light purple 0;36 cyan 1;36 light cyan 0;37 light gray 1;37 white |
A few useful additions.
The PS1 line above is dense — here’s what each piece is doing:
1 2 3 4 5 6 7 8 9 | \[ ... \] tells bash "these characters are non-printing" so it computes prompt width correctly (otherwise long commands wrap weirdly) \e[1;32m ANSI escape: bold (1) green (32) \u current username \h short hostname \t current time, 24-hour HH:MM:SS \w full working directory \$ '#' if you're root, '$' otherwise \e[0m reset all colors/attributes back to default |
You can preview a color in your terminal without touching .bashrc by echoing the escape sequence directly:
1 2 | echo -e "\e[1;32mhello in bold green\e[0m" echo -e "\e[0;35mhello in purple\e[0m" |
That’s the fast way to audition a color before committing to it in your prompt.
For background colors, the codes run 40 to 47 (same intensity rule applies). To make the whole prompt have a colored background, combine them:
1 2 | PS1='\[\e[1;33;44m\][\u@\h \w]\$\[\e[0m\] ' # bold yellow text on a blue background |
One portability note: hard-coded ANSI escapes work everywhere bash runs, but if you’re writing scripts that should adapt to different terminal types, tput is the modern, terminfo-aware alternative:
1 2 3 4 5 | GREEN=$(tput setaf 2) BOLD=$(tput bold) RESET=$(tput sgr0) echo "${BOLD}${GREEN}status: ok${RESET}" |
tput queries the terminfo database for whatever terminal you’re actually on, so it gracefully degrades on terminals that don’t support color (it just emits empty strings). For your personal .bashrc, raw ANSI is fine and shorter; for scripts you ship to other people’s machines, tput is the polite choice.
After editing, reload your shell config with source ~/.bashrc (or just open a new terminal) to see the change.