Monday, March 7, 2011

Bash PS1 Colors and More Space

function prompt_color() {
local gr='\033[0;32m' # light green
local red='\033[0;31m' # light red
local bold_red='\033[1;31m';

if [ $1 -ne 0 ]; then
  echo -e "${bold_red}**${1}**${red}"
  return
fi

echo -e "$gr"
}

function prompt() {
local nc='\033[0m' # no color

# User@{2 part hostname} date time directory\nCommand Number $ - me, # - root
# __git_ps1 - show current git branch; http://blog.jasonmeridth.com/2010/05/22/git-ps1.html
local $ps1='[\u@$SHORTNAME \D{%Y-%m-%d} \t \W$(__git_ps1 " (%s)" 2>/dev/null)]'

export PS1=$(echo '$(prompt_color $?)' "'$ps1'" "$nc" ' \n[\!]\$ ');
}


I also employ `echo` above in order to concatenate the color variables with the PS1 string, which should be evaluated ONLY per PS1, not at the time of definition. I originally was using double quotes to surround the entire thing, but then realized that `git_ps1` was getting executed ONLY when PS1 was being defined.



UPDATE: I have made some changes. See https://gist.github.com/asheepapart/6243750. Here's the screenshot:


2 comments:

  1. You should screenshot your terminal with that PS1 see what it looks like.

    ReplyDelete
  2. Thanks! This is just what I was looking for. Coloring a bash terminal from a function is very unintuitive. Your code is great!

    ReplyDelete