Playing with my Prompt

Posted by Fred Jean on October 19th, 2006 in Uncategorized

Up until a few days ago, I saw no reasons to change the shell prompt on my systems. It all looked a little different, but I was ok with it. Well, that changed last night while I attended a presentation at the Boulder-Denver Ruby Users Group. Ara, the presenter, had modified his prompt to show whether the previous command had succeeded or not. I decided to do the same to my systems. I came up with the following code added to my .bash_profile (with a lot of help from the Bash Prompt Howto) :

function my_prompt() {
   # Determines whether the previous command succeeded...
   if [ $? -eq 0 ]; then
      result="1;32m:)"
   else
      result="1;31m:("
   fi
   pwd_length=20
   DIR=`pwd`
   echo $DIR | grep "^$HOME" >> /dev/null
   if [ $? -eq 0 ]
   then<
      CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'`
      newPWD="~$CURRDIR"
      if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
      then
         newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
      fi
   elif [ "$DIR" = "$HOME" ]
   then
      newPWD="~"
   elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
   then
      newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
   else
      newPWD="$(echo -n $PWD)"
   fi
}
export PROMPT_COMMAND=my_prompt
PS1='33[1;30m\[33]2;\u@\h:${newPWD}\a\]\
[\u@\h ${newPWD}]\n33[${result} 33[1;30m\$ 33[0;39m'

As a result, this is what I now see in my terminal windows when things go well:

[fjean@voyager ~]:) $

And when things go bad:

[fjean@voyager ~/..ojects/yagrails-test]:( $

I have configured my work system and my PowerBook to use the new prompt. I have also added a few other tricks to my work desktop (such as setting the terminal window's title based on where I am in my file system).

Note: I did try to convey the colors, but it appears that Ecto and WordPress conspired to strip them away… I'll keep trying though…

1 Responses »

  1. Very cool. Thanks for sharing.





Find us on LinkedIn Add us on Facebook! Add us on Google Plus! Chat with Us

Archives

Categories

About Us

OpenLogic helps enterprises use open source software by providing open source support, scanning, governance, and cloud solutions. For more on OpenLogic, go to www.openlogic.com.