How to Set Up Color in Bash Prompt with Escape Sequences?

April 21, 2025 1 answer
Asked by sun-dried laundry
Hey everyone! I'm trying to customize my Bash prompt and I've hit a snag with handling ANSI escape sequences for colors. Here's what I've tried so far, but it isn't working: ```bash RED='e[38;5;203m' GREEN='e[38;5;41m' RESET='e[0m' function prompt_status() { # Set prompt color based on previous command status if [ $? -ne 0 ]; then PROMPT_COLOR=$RED else PROMPT_COLOR=$GREEN fi } PROMPT_COMMAND=prompt_status PS1="$PROMPT_COLOR$ $RESET" ``` I've gone through the Bash manual to refresh on expansions, but I'm stuck. I've tried different methods like curly braces and escape sequences, but nothing seems to work for the `PS1` variable. I'm particularly looking for resources on why this doesn't function as intended and how to effectively script colors for prompts since I want my color setup to be clean and consistent across Bash, Zsh, Fish, and Tmux. Any advice would be greatly appreciated! Thanks!

Answers

PAVEMENT ENDS
It looks like your issue is with the use of double quotes in the `PS1` assignment. The color variable only gets expanded once when you set `PS1`, which means at that point, `$PROMPT_COLOR` is still empty because `prompt_status()` hasn't run yet. If you want it to update dynamically, you need to make sure your `PS1` has the correct structure with single quotes that allow it to evaluate each time the prompt is drawn instead of at assignment.

sun-dried laundry: Solved! I didn't realize the `PS1` was in single quotes, which was the whole issue. I spent so long changing everything else. Thanks a ton!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions