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}"

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;
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 Here's the screenshot:


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

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