Jason McCreary
Jason McCreary

Reputation: 72961

bash prompt coloring for Mac OS X

The Goal

I'm trying to colorize my bash prompt on Mac OS X with the git branch (where available).

What I've Tried

With my limited bash knowledge, I pieced together the following code from Google searches and other questions:

function parse_git_branch() {
        branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

        if [[ -z "$branch" ]]; then
                return
        fi

        if [[ -z "$(git status -s 2>/dev/null)" ]]; then
                color=$'\e[1;32m'
        else
                color=$'\e[1;31m'
        fi

        echo "\[$color\] (${branch}) "
}

PS1="\h:\W \u\$(parse_git_branch)\[\e[0m\]\$ "

The Problem

While the coloration works, the prompt contains some of the escape sequences from parse_git_branch.

leonidas:AYI jason\[\] (master) $

In addition, things like command history (up) and recursive search (ctrl+r) yield extra characters.

leonidas:AYI jason\[\] (master) $h)`re': git status

The Questions

  1. How can I fix the escaping with proper visible and non-visible characters.
  2. Should I use tput instead of these color codes for wider support?

Upvotes: 1

Views: 5369

Answers (2)

that other guy
that other guy

Reputation: 123400

The problem is that \[ \] is not respected in expanded data.

To get around it, you can set PS1 to a post-expansion version of itself in PROMPT_COMMAND, whose contents is evaluated before every prompt:

PROMPT_COMMAND='PS1="\h:\W \u$(parse_git_branch)\[\e[0m\]\\\$ "'

Since the \[ \] are now part of the literal value of PS1, and not created by prompt expansion, they're correctly interpretted.

Upvotes: 2

Milliways
Milliways

Reputation: 1275

Why go to all this trouble. Just create a .bash_profile Mine is:-

export PS1="\[\033[0;30;33m\]\w\[\e[0m\]$ "

You should set .bashrc to reference this

[ -r ~/.bash_profile ] && source ~/.bash_profile

Upvotes: 3

Related Questions